|
-
July 4th, 2002, 11:57 PM
#1
String To Hex
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
Bengi
-
July 5th, 2002, 04:48 AM
#2
There is a fast way but it is *VERY* expensive in terms of space.
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]];
Basically anything outside the range is 0. So 123XYAF would convert to 12300AF. I only use it if time is a critical issue.
Succinct is verbose for terse
-
July 5th, 2002, 04:52 AM
#3
Re: String To Hex
I'm sure the code below is not the best solution. However is faster than others. I hope it'll help you.
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;
}
Regards,
ZDF
What is good is twice as good if it's simple.
"Make it simple" is a complex task.
-
July 5th, 2002, 05:16 AM
#4
Both zdf and I have the same solution: it is just the initialization that is different.
Succinct is verbose for terse
-
July 5th, 2002, 10:56 AM
#5
The simple solution is to use sscanf()
char str[]="2E5F1D";
DWORD hexnum;
sscanf(str, "%x", &hexnum);
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|