|
|
发表于 2010-1-19 19:51:31
|
显示全部楼层
util.cpp
#include "util.h" - p- j: W% ?% o: _+ r1 D
#include <vector> ( Q$ k$ z5 X! |& ]6 \% |, z* R
. @& N$ n9 Q& n% S
using namespace std; ( u) z7 H1 h( V: b) O
- k$ F {, I$ h( E+ x, {2 Z+ c
char intToHexChar(int x) {
( h4 w) v2 w; K static const char HEX[16] = { . W) [8 h0 O+ c0 ^
'0', '1', '2', '3',
' ^* t0 V$ Q+ e- @" h! w3 | '4', '5', '6', '7',
) I7 S N+ {6 p( u( b; d '8', '9', 'A', 'B',
" B; X, s1 X% {: \% C 'C', 'D', 'E', 'F'
# x; }6 H9 q1 e1 f/ t };
9 z9 X4 s3 m$ O+ m5 z return HEX[x]; $ o9 r5 p/ C$ j, o1 f
} w% B$ l* v- ~& D$ k( V+ ?
u/ e( x8 _7 h4 r4 v3 _( U' d# J; wint hexCharToInt(char hex) { , i$ i* e+ o4 s9 F: j; U
hex = toupper(hex);
# y# c+ W( |+ E) a. w. m if (isdigit(hex))
; C8 `% X# v1 W6 ?3 |5 `% e2 o Y return (hex - '0'); / x3 l1 G0 [" H0 s8 y/ Y! k d
if (isalpha(hex)) . q' j* t+ q2 F
return (hex - 'A' + 10);
: o4 r; V8 x; O8 I% h% ? return 0;
1 s* Q( o# P; L3 Q& ?} " l+ S( q+ @) A# s9 f, I! v3 E! s
4 b8 V* x a! Y7 x8 D N# h
string bytesToHexString(const byte *in, size_t size) { ; S" j( [8 `+ o
string str;
3 N% [7 ^3 [ _ for (size_t i = 0; i < size; ++i) { 9 Z% ]0 E8 J6 B+ d" T6 t
int t = in[i];
$ P# g0 Z: C' C9 J% J int a = t / 16;
" M$ e$ n7 p0 E# N$ I% R int b = t % 16;
' z1 J' y$ m# d9 T6 Z str.append(1, intToHexChar(a)); 8 z* }) H' e7 t8 I$ _5 h
str.append(1, intToHexChar(b));
/ K% `, f0 U. w' p7 n0 { if (i != size - 1)
% P( X& H' R D6 | str.append(1, ' ');
' U3 @8 V) ^& F3 Q/ o" E6 ? } ! ~0 T( D' N: Q+ \
return str;
4 ]7 L; W8 R8 R8 r0 d, [9 [" ]} # ~, z* x' e: R7 N1 O' M, A: B( Y
0 }6 q6 v3 J& Z5 q- U* zsize_t hexStringToBytes(const string &str, byte *out) {
2 v2 U4 w1 X5 O: l 4 A0 Y5 d7 ~8 q, Y) a3 Z2 R; A
vector<string> vec;
4 Y* v7 [3 o8 @# j5 L string::size_type currPos = 0, prevPos = 0; 0 V8 o& T: i- u" w5 |+ y
while ((currPos = str.find(' ', prevPos)) != string::npos) {
' N$ n: ^" r" ] string b(str.substr(prevPos, currPos - prevPos));
, H3 n9 f: P9 F/ F. f2 `0 Z& p7 i; I vec.push_back(b); 4 A# {: e. Q; l
prevPos = currPos + 1; 2 X, u/ ^( N* |) ?$ e
}
% z+ c! _0 q. O5 V9 y- C+ x1 Z2 l if (prevPos < str.size()) { ) R ]! g7 @9 o ~ p# N% [$ |. _9 a5 B
string b(str.substr(prevPos));
$ l2 b8 V2 N* n; @ vec.push_back(b);
( _, w% C. }0 `$ u* N$ o6 G }
$ G" p# k1 a$ A, R* }% W; J typedef vector<string>::size_type sz_type; 4 j" M- E5 D1 j
sz_type size = vec.size();
( @* z3 r0 I( h) w& C& I9 Z) B8 m/ b/ C for (sz_type i = 0; i < size; ++i) {
4 D& I" [# s0 f int a = hexCharToInt(vec[i][0]); ; ^. [5 v' y' N, g, @6 G8 G' P$ v( u* f
int b = hexCharToInt(vec[i][1]);
$ q3 O! [4 J6 d: Q% m' J out[i] = a * 16 + b;
5 h7 f7 y+ _- S; @ }
# f6 V( v; t7 `. N1 Q: e return size; 6 _0 m2 v0 H; y8 C0 A; N
} |
|