Home > Blockchain >  what happens when %x read signed char?
what happens when %x read signed char?

Time:06-27

enter image description here

i thought *(p3 3) will print 90 but it shows ffffff90 why does it happend? i guess MSB is 1, and %x is for reading unsinged hexadecimal integer so it reads 90 like minus integer but it is not clear and i cant find about this problem at printf reference https://cplusplus.com/reference/cstdio/printf/ is there anyone who explain this?

CodePudding user response:

Use an unsigned char *.


In your environment,

  • char is signed.
  • char is 8 bits.
  • Signed numbers use two's complement.

So you have a char with a bit pattern of 9016. In this environment, that's -112. So you are effectively doing the following:

printf( "%x", (char)-112 );

When passing to variadric function like printf, the smaller integer types are implicitly promoted to int or unsigned int. So what's really happening is this:

printf( "%x", (int)(char)-112 );

So you're passing the int value -112. On your machine, that has the bit pattern FF FF FF 9016 (in some unknown byte order). %x expects an unsigned integer, and thus prints that bit pattern as-is.

  • Related