Possible Duplicate:
Hex to char array in C
I have a char[10] array that contains hex characters, and I'd like to end up with a byte[5] array of the values of those characters.
In general, how would I go from a char[2] hex value (30) to a single decimal byte (48)?
Language is actually Arduino, but basic C wou开发者_JAVA百科ld be best.
1 byte = 8 bit = 2 x (hex digit)
What you can do is left shift the hex-digit stored in a byte by 4 places (alternatively multiply my 16) and then add the 2nd byte which has the 2nd hex digit.
So to convert 30 in hex to 48 in decimal:
- take first hex digit, here 3; multiply it by 16 getting 3*16 = 48
- add the second byte, here 0; getting 48+0 = 48 which is your final answer
Char array in "ch", byte array as "out"
byte conv[23] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15};
// Loop over the byte array from 0 to 9, stepping by 2
int j = 0;
for (int i = 0; i < 10; i += 2) {
out[j] = conv[ch[i]-'0'] * 16 + conv[ch[i+1]-'0'];
j++;
}
Untested.
The trick is in the array 'conv'. It's a fragment of an ASCII table, starting with the character for 0. The -1's are for the junk between '9' and 'A'.
Oh, this is also not a safe or defensive routine. Bad input will result in crashes, glitches, etc.
精彩评论