I have a character array (an ethernet address like aa:bb:cc:dd:ee:ff) that I need to parse up into an unsigned char[6]. I’m using strtok to get each pair of characters, and I need to cast them into an unsigned char, but nothing I’m doing is working.
I’ve tried (assume c is a char* of length 2):
unsigned char t = (unsigned char)c; // gives "loses precision" error
unsigned char* t = (unsigned char*)c;
unsigned char t1 = t[0]; // gives the wrong value
unsigned char t;
strcpy((char*)t, c); // gives the wrong value
strncpy((char*)t, c, sizeof(char)*2) // gives the wrong value
Assuming that your input string is a hex string containing at most two hexadecimal numbers, i. e.
FFyou can usestd::stringstreamto do the conversion:You’ll have to ensure, that
creally is not bigger thanFF.EDIT: Changed the above code to read the value into an
intfirst and then cast it tounsigned char. When reading directly into acharit’s reading characters only without any conversion.