Printing hexadecimal characters in C

Rayne picture Rayne · Nov 9, 2011 · Viewed 357.1k times · Source

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?

Answer

Mysticial picture Mysticial · Nov 9, 2011

You are seeing the ffffff because char is signed on your system. In C, vararg functions such as printf will promote all integers smaller than int to int. Since char is an integer (8-bit signed integer in your case), your chars are being promoted to int via sign-extension.

Since c0 and 80 have a leading 1-bit (and are negative as an 8-bit integer), they are being sign-extended while the others in your sample don't.

char    int
c0 -> ffffffc0
80 -> ffffff80
61 -> 00000061

Here's a solution:

char ch = 0xC0;
printf("%x", ch & 0xff);

This will mask out the upper bits and keep only the lower 8 bits that you want.