简体   繁体   中英

C Programming - Printing Hexedecimal Character Whose Most Significant Bit is 1

The code snippet

char c1;
char c2;
c1 = 0X7F;
c2 = 0X80;
printf("c1 = %X\nc2 = %X\n", c1, c2);

outputs

c1 = 7F
c2 = FFFFFF80

why is it that c2 does not print as 80 ? (i'm guessing it's something to do with the fact that the most significant bit of 0X80 is 1 while the MSB of 0x7F is 0). how can i get c2 to print as simply 80 ?

Because printf is a variadic function . Arguments to variadic functions undergo the default promotions ; one effect of this is that char arguments are converted to int . On your platform, char is signed , so c2 is actually negative. printf is therefore printing all the leading ones that occur in the int (these are due to two's-complement representation).

There are (at least) 3 methods to work around this:

  • Use %02X rather than %X as your printf format specifier.
  • Use unsigned char rather than char (this gets promoted to unsigned int , so no leading ones)
  • Explicitly convert each of your char s to int , and then mask: (int)c2 & 0xFF .

[ Note: The corollary of this is that the behaviour of char c2 = 0x80 is actually implementation-defined; if char is signed then this will overflow. ]

c2 gets (sign-)extended to int . The following will do what you require:

printf("c1 = %X\nc2 = %X\n", c1, ((int)c2) & 0xFF);

Try unsigned char to print as per your need. Here is a ideone sample

unsigned char c1;
unsigned char c2;
c1 = 0X7F;
c2 = 0X80;
printf("c1 = %X\nc2 = %X\n", c1, c2);

As mentioned already the output you are seeing is due to sign extension.
Hope this helps!

in order to force printf to treat that as a character, you need to give the "hh" modifier. try:

printf("c1 = %hhX\nc2 = %hhX\n", c1, c2);

You're passing char s and having them read as unsigned int s, you're lucky it works at all. That said, char is signed. 0x80 actually makes it negative. They are apparently being converted to ints and then unsigned. That extends the sign bit, thence the f s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM