|
|
发表于 2010-1-19 19:51:31
|
显示全部楼层
util.cpp
#include "util.h" ; S) k2 ~8 f, Q/ G3 \- Y. X
#include <vector>
' F4 O, A$ y. Y4 f6 i
% h1 C* z! H; K& n% R* ^4 ~using namespace std;
' _# j( U, z; \2 C# b5 u7 ^. g
5 |, U- X s! j; b! T6 f, Q4 a, gchar intToHexChar(int x) { ! l7 B8 h- O: S; O6 |4 j
static const char HEX[16] = {
. g) R9 C! C: f7 ~/ s8 @ '0', '1', '2', '3', " V2 P/ P t; W# R5 A/ W& E8 B
'4', '5', '6', '7',
$ I6 ]: A8 w! W' | '8', '9', 'A', 'B', 3 ^+ b! G, l- c! v$ J! R7 O: K
'C', 'D', 'E', 'F'
; K; k" j# y) X$ F( i, b" N( E( M };
* a# n6 ], ~$ h- D' u2 I* i return HEX[x];
3 r! C" C0 D3 p; T} - p& a6 b2 }8 [5 P
4 B S7 Y+ M# V3 h2 N; a! D1 w/ `$ o
int hexCharToInt(char hex) { ) z N9 m4 X7 y( E: Y8 U
hex = toupper(hex); ! Y2 t+ N' ~3 @& |# E4 T
if (isdigit(hex))
4 M( C2 }& V/ C return (hex - '0');
' g7 \6 x; f8 G9 @3 q. p if (isalpha(hex))
7 l5 X& {+ h" l5 P- g% g return (hex - 'A' + 10);
; A, Z9 Y) E2 t* s/ L3 } return 0;
) M! O- S* D( C) d$ l6 _1 R5 z}
* A+ y5 g7 G0 ?3 T; W5 Z
4 ^1 x3 H" Y' U6 |! y3 X: ostring bytesToHexString(const byte *in, size_t size) { $ v7 e' |" n2 d- _1 J, O( u( R
string str;
9 V3 n# U2 a: _1 m# B8 C5 {1 s9 o for (size_t i = 0; i < size; ++i) { ' Y" u* y. v2 A/ c
int t = in[i]; ) n8 y# w- ]9 F' Y, u! p
int a = t / 16; ' E% C" c7 t0 P8 _7 M
int b = t % 16;
, B) T0 ^2 s5 x& v0 e8 L str.append(1, intToHexChar(a));
3 i, D( c4 X: {6 ?9 _4 G str.append(1, intToHexChar(b)); 6 g6 h6 y* C5 W$ P
if (i != size - 1)
3 E( J- h2 R* L5 `6 c str.append(1, ' '); 2 l8 N7 b! t# h8 y
} * [& n9 @3 I+ o4 A8 A" t8 Z# K
return str;
; i$ }* z7 y& T- A& Q( H! p. i}
+ X9 x# o. J X! C5 J: @2 L t8 x" k- W3 s5 D, Z( |
size_t hexStringToBytes(const string &str, byte *out) {
- o! i# R* w& H4 S 5 c' z$ \' O6 m$ V" o
vector<string> vec; 9 I8 N; c4 `7 c8 ^) n9 I& A- r& O
string::size_type currPos = 0, prevPos = 0;
1 T6 e+ s; u0 u5 g6 I( @ while ((currPos = str.find(' ', prevPos)) != string::npos) { 7 w2 u: F _: z2 M y! S4 w
string b(str.substr(prevPos, currPos - prevPos)); / e) B& a7 ~% r
vec.push_back(b);
, N2 `! ]) s- w3 G' P prevPos = currPos + 1;
/ I2 M& B3 b6 y+ E8 v } 0 v4 o* w/ l7 ]3 g* V# i
if (prevPos < str.size()) { # }& N- `! B9 g8 j. }, ^
string b(str.substr(prevPos));
9 X5 ?7 d( E, ]* y/ ~/ f vec.push_back(b);
1 D: j4 g) L' M' a6 G- y }
; K. L1 A6 J: c5 h$ y" _# ~, O typedef vector<string>::size_type sz_type;
- y7 X1 W, X; w sz_type size = vec.size();
+ n, l2 a4 M; l, t$ t4 Q7 B* U& q# t for (sz_type i = 0; i < size; ++i) { 9 n I9 u M }( |) F
int a = hexCharToInt(vec[i][0]);
# t- X& t# @% f% ~8 J int b = hexCharToInt(vec[i][1]); 3 R6 ? e( A6 t
out[i] = a * 16 + b;
/ p" {! m. k' ?6 x$ v) R } - V$ ?$ C: R0 h2 d$ m9 x
return size;
3 C* n; R, u/ D5 r8 h} |
|