I'm trying to read in a line of characters, then print out the hexadecimal equivalent of the characters.
For example, if I have a string that is "0xc0 0xc0 abc123"
, where the first 2 characters are c0
in hex and the remaining characters are abc123
in ASCII, then I should get
c0 c0 61 62 63 31 32 33
However, printf
using %x
gives me
ffffffc0 ffffffc0 61 62 63 31 32 33
How do I get the output I want without the "ffffff"
? And why is it that only c0 (and 80) has the ffffff
, but not the other characters?
You are probably storing the value 0xc0 in a
char
variable, what is probably a signed type, and your value is negative (most significant bit set). Then, when printing, it is converted toint
, and to keep the semantical equivalence, the compiler pads the extra bytes with 0xff, so the negativeint
will have the same numerical value of your negativechar
. To fix this, just cast tounsigned char
when printing: