hi all,
is there a fast way to make a String, ie: chat str[]="2E5F1D"
transform to an hex number with same value, i.e: DWORD hexnum=0x2E5F1D, ?
thnx all
Printable View
hi all,
is there a fast way to make a String, ie: chat str[]="2E5F1D"
transform to an hex number with same value, i.e: DWORD hexnum=0x2E5F1D, ?
thnx all
There is a fast way but it is *VERY* expensive in terms of space.
Basically anything outside the range is 0. So 123XYAF would convert to 12300AF. I only use it if time is a critical issue.Code:// initialization
DWORD lookup[256];
memset (lookup, 0, sizeof (lookup));
lookup['0'] = 0;
lookup['1'] = 1;
..
lookup['A'] = 10;
...
lookup['F'] = 15;
lookup['a'] = 10;
...
lookup['f'] = 15;
// conversion of str
DWORD value = 0;
for (int i = 0; str[i]; i++)
value = (value << 4) | lookup[str[i]];
I'm sure the code below is not the best solution. However is faster than others. I hope it'll help you.
Regards,Code://-------------------------------------------------------------------------
/*
No white
No checking: the string must be a hex number
*/
unsigned int htoi(const char* s)
{
static unsigned int h[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0,
0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
unsigned int t = 0;
while ( *s )
{
t <<= 4;
t += h[*s++];
}
return t;
}
int main()
{
unsigned int i = htoi("2E5F1D");
return 0;
}
Both zdf and I have the same solution: it is just the initialization that is different.
The simple solution is to use sscanf()
char str[]="2E5F1D";
DWORD hexnum;
sscanf(str, "%x", &hexnum);