Oct 21, 2012 at 4:29pm UTC
I have a data file with hex values representing a byte of data per two hex characters. I have to stream in this data, and I'm currently streaming this data from the file and putting the result, line by line, into a string:
2 3 4 5 6 7 8 9
Let's say a given line is "0123456789abcdef". I would like to take this string, break it up, and store the hex values as characters. Essentially, the same result as doing this:
2 3 4 5 6 7 8 9 10 11 12 char a;
a = 0x01;
b = 0x23;
c = 0x45;
c = 0x67;
c = 0x89;
c = 0xab;
c = 0xcd;
c = 0xef;
I need some advice as to how I could achieve this result. So far I have attempted to use many methods, including string.copy() to copy parts of the string to a character array:
length = line.copy(c,12,4);
But this approach isn't anywhere close to correct. It stores the values as:
2 3 4 5 6 7
c = '1';
c = '2';
c = '3';
c = '4';
c = '5';
It may be that the best method is to stream the hex values directly into the characters, but I am also unsure how I would do that. Any help is appreciated.
Last edited on
Oct 21, 2012 at 4:33pm UTC
Oct 21, 2012 at 5:36pm UTC
Well, you need to convert each pair of chars in the string into a single byte.
Each char corresponds to a nybble (or nibble) which has a value 0-F. So you need to convert the char to the corresponding value, hex-wise: 0->0, 1->1, ... E->14, F->15
Then a byte value = high_nybble * 16 + low_nybble (or you can use bit shifting)
Last edited on
Oct 21, 2012 at 5:37pm UTC
Oct 21, 2012 at 6:29pm UTC
Well, I would implement it using if()s...
You don't really need atoi when you are converting a single char. And you can exploit the fact the ranges '0', '1', '2', ... and 'a' ... 'f' are contiguous.
Also, the code for the low and high order nybbles is identical, so could be factored out into a helper function.
Oct 21, 2012 at 8:00pm UTC
Thank you very much. That answers my question.