Printing hexadecimal characters in C

2019-01-01 13:17发布

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?

标签: c hex printf
7条回答
无与为乐者.
2楼-- · 2019-01-01 13:53

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 to int, and to keep the semantical equivalence, the compiler pads the extra bytes with 0xff, so the negative int will have the same numerical value of your negative char. To fix this, just cast to unsigned char when printing:

printf("%x", (unsigned char)variable);
查看更多
登录 后发表回答