View previous topic :: View next topic |
Author |
Message |
Linuxbuilders
Joined: 20 Mar 2010 Posts: 193 Location: Auckland NZ
|
CHAR into HEX |
Posted: Fri Aug 06, 2010 11:10 pm |
|
|
Hi,
I am trying to do this but can't get it working, can you help please.
From terminal I enter ASCII: AADD and need to convert it into 0xAADD inside the program, so far I am getting 0x41 0x41 0x44 0x44 which is not what I am looking for.
I process a string where AADD is respectively string[1,2,3,4]
thnx _________________ Help "d" others and then you shell receive some help from "d" others. |
|
|
newguy
Joined: 24 Jun 2004 Posts: 1907
|
|
Posted: Fri Aug 06, 2010 11:32 pm |
|
|
Code: | int32 my_hex_number = 0;
for (i = 0; i < 4; i++) {
if (string[i] >= 0x30 && string[i] <= 0x39) { // ascii 0 - 9
my_hex_number = (my_hex_number << 4) + (string[i] - 0x30);
}
else { // ascii a - f, but you should do a bounds check to be sure
my_hex_number = (my_hex_number << 4) + (string[i] - 0x37);
}
} |
This little bit of code just searches through your string[] array, iteratively subtracting the ascii "offset" from the entry in string[], and adding that to whatever was stored in my_hex_number previously, multiplied by 16 of course. |
|
|
Linuxbuilders
Joined: 20 Mar 2010 Posts: 193 Location: Auckland NZ
|
|
Posted: Sat Aug 07, 2010 12:38 am |
|
|
Thank you, with little mod it works well.
Thank you _________________ Help "d" others and then you shell receive some help from "d" others. |
|
|
Linuxbuilders
Joined: 20 Mar 2010 Posts: 193 Location: Auckland NZ
|
|
Posted: Sun Jun 16, 2013 3:28 am |
|
|
Hey, found it in my "bag" of old code
Code: |
ascii_convert(int value) { // ASCII conversion
int output = 0;
int strng = 0;
strng = value;
if (strng >= 0x30 && strng <= 0x39) { // ascii 0 - 9
output = strng - 0x30;
}
else { // ascii a - f
output = strng - 0x37;
}
return(output);
} |
_________________ Help "d" others and then you shell receive some help from "d" others. |
|
|
ckielstra
Joined: 18 Mar 2004 Posts: 3680 Location: The Netherlands
|
|
Posted: Sun Jun 16, 2013 4:00 pm |
|
|
Thanks for sharing your code, but why after 3 years? And for a topic that has been discussed on this forum countless times?
Also, your posted code does not answer your original question:
- it converts only 1 hexadecimal character, not 4 as asked in the original topic.
- this code only handles lower case hexadecimal values but the original question was in capital characters.
Here is a more optimized solution: http://www.ccsinfo.com/forum/viewtopic.php?t=49776 |
|
|
|