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:
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:
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:
1 2
length = line.copy(c,12,4);
c[length] = '\0';
But this approach isn't anywhere close to correct. It stores the values as:
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.
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)
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.
Sure, there will always be ways to do things differently. Below is how I would do it:
1 2 3 4 5 6 7 8 9
char hexchar; // assume this is one of the chars (ABCDEFabcdef)
int hexvalue;
if (hexchar >= 'A' && hexchar <= 'F') {
hexvalue = hexchar - 55;
}
elseif (hexchar >= 'a' && hexchar <= 'f') {
hexvalue = hexchar - 87;
}
Now, before you use that, make sure you understand what it does. Make sure to try to understand it yourself (try not to ask anyone). It is pretty straight forward anyways.