0

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 would be best.

Community
  • 1
  • 1
Loki
  • 6,205
  • 4
  • 24
  • 36
  • Depends on the character set. For ASCII I've been using a constant array of offsets between the value per nybble and the character value. Because one byte is two nybble at most. – 0xC0000022L Apr 22 '11 at 04:06
  • it isn't an exact duplicate of the existing questions, but the hex2bin function answer on the linked question works well in this situation with modifications. Essentially, making it only operate on two chars at a time, and passing in a ref to my char array. – Loki Apr 24 '11 at 05:50

2 Answers2

0

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:

  1. take first hex digit, here 3; multiply it by 16 getting 3*16 = 48
  2. add the second byte, here 0; getting 48+0 = 48 which is your final answer
BiGYaN
  • 6,974
  • 5
  • 30
  • 43
0

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.