|
发表于 2010-1-19 19:51:31
|
显示全部楼层
util.cpp
#include "util.h" - p6 F, c5 _, m9 Y+ ^
#include <vector> % M4 P# y9 |; a8 }8 r
5 Z2 o% u% x% Y+ i O8 Susing namespace std;
8 N7 c8 n( T8 m& H3 `* D+ _
z# k) r: ^ ~1 Ochar intToHexChar(int x) { ; y4 d7 j& V9 ~, y( y! }
static const char HEX[16] = { % M1 ^" B( q2 p6 Q- g2 _/ @
'0', '1', '2', '3',
, M" F0 a8 V3 b$ L& B7 Q '4', '5', '6', '7',
- B$ P6 `) D: s, Z$ i2 X '8', '9', 'A', 'B',
5 `2 a7 e7 G8 d; t$ N) |0 C 'C', 'D', 'E', 'F'
! y+ f9 J. _* Z3 l };
& ?* _9 \- O0 {& B# B$ w+ I return HEX[x]; / m8 ~$ |8 U$ Z$ U# o
} & i6 y! {+ F+ b3 `7 {9 D8 C$ t
8 `# w3 d% Z' s5 w, T5 Gint hexCharToInt(char hex) {
9 b1 p) x) s/ G) u1 k1 {) ^8 V hex = toupper(hex);
* l* @# p2 @1 _. A+ y. e: @ if (isdigit(hex)) * R! Z* i4 u( B8 ^. o
return (hex - '0'); 1 F$ X$ y& \ u
if (isalpha(hex))
( D7 h. o& t, z3 h$ I return (hex - 'A' + 10); . S7 K y# I% ]* X, t. b
return 0; 2 ]2 t2 N0 G& _* D S/ Y3 K
}
8 U; D& x! k0 E/ k' E* P& N9 W * e6 c2 X( }" g# R
string bytesToHexString(const byte *in, size_t size) {
8 ?; ^8 \: C8 g U* @/ z string str; 0 y- F$ @' l* r/ a; Y( n; W8 x2 ]
for (size_t i = 0; i < size; ++i) {
+ w% t B H8 M/ X3 `, b int t = in[i];
# A) N5 L% r# b# Q! L/ u, A7 @ int a = t / 16; 6 Q- _& c3 n! x0 {7 g
int b = t % 16;
9 B, i8 T/ g# b" {/ c- h& t str.append(1, intToHexChar(a)); $ |, D3 d% @: ]$ c o- V* W
str.append(1, intToHexChar(b)); : B$ P$ A4 C% ~$ `
if (i != size - 1) " V3 t7 s3 S' b* G+ o
str.append(1, ' '); ! Y1 J. o9 K9 X
} ! a) _; n; E9 A9 Q6 u9 i/ H& u
return str; ) L& `0 m) W: Y5 Q G
}
+ J& A# L( a! }/ z, |. P
" i) v$ w- d- Z. B& t4 Z* Hsize_t hexStringToBytes(const string &str, byte *out) {
4 ~$ G! y# O, B5 | " j/ l! y% z' @# l0 @
vector<string> vec;
3 c( g g2 W9 n2 Z5 [* [ string::size_type currPos = 0, prevPos = 0; 5 J& B; B9 N+ t# U, b( a# R! D
while ((currPos = str.find(' ', prevPos)) != string::npos) {
( _0 [+ ?, i$ Y2 S: y string b(str.substr(prevPos, currPos - prevPos));
6 R3 q* a3 u, B$ Y2 y6 C, F4 L vec.push_back(b);
* u4 c* m6 d( g prevPos = currPos + 1; 4 ?3 ^# q! y" f, K7 s
} # u, l n* F# |; q
if (prevPos < str.size()) { : _/ T5 z$ Y" {# D% c# p( d
string b(str.substr(prevPos));
1 t" {( c* Y) E) x7 C, v, I vec.push_back(b); * r, L' Q* [ v; P4 g
}
2 C( ?1 k+ {. `) ~! j typedef vector<string>::size_type sz_type; / s4 A% n; [# d7 b1 B3 q
sz_type size = vec.size();
5 A' D4 T W% \3 h1 X7 k2 M0 W for (sz_type i = 0; i < size; ++i) {
3 X1 D4 @" r) f0 E7 I" K6 \; I int a = hexCharToInt(vec[i][0]); # v% N: r6 R) e# D7 x5 D1 a4 A
int b = hexCharToInt(vec[i][1]); # X& F' S5 s# y8 q
out[i] = a * 16 + b;
5 r* e. g# G3 j8 T+ \* ~ }
P- @3 L+ s. Z8 c return size;
; \! h/ T, `: c6 M5 x/ K* ?} |
|