Click to See Complete Forum and Search --> : String To Hex


Bengi
July 4th, 2002, 11:57 PM
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

cup
July 5th, 2002, 04:48 AM
There is a fast way but it is *VERY* expensive in terms of space.


// 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]];


Basically anything outside the range is 0. So 123XYAF would convert to 12300AF. I only use it if time is a critical issue.

zdf
July 5th, 2002, 04:52 AM
I'm sure the code below is not the best solution. However is faster than others. I hope it'll help you.

//-------------------------------------------------------------------------
/*
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;
}


Regards,

cup
July 5th, 2002, 05:16 AM
Both zdf and I have the same solution: it is just the initialization that is different.

stober
July 5th, 2002, 10:56 AM
The simple solution is to use sscanf()


char str[]="2E5F1D";
DWORD hexnum;
sscanf(str, "%x", &hexnum);