Home > Mobile >  Does printf() print with endianness?
Does printf() print with endianness?

Time:10-19

I have a small snippet:

int main()
{
        unsigned long long x = 0x0000000000008342;
        unsigned long long * x_p = &x;
        unsigned int * y_p = (unsigned int *)x_p;
        unsigned int y = *y_p;
        printf("y = %#.8x\n", y);
}

With little endian, this is how a number is stored.

0x00: 42 83 00 00
0x04: 00 00 00 00

But instead of 0x00004283, why does it print 0x00008342 ?

CodePudding user response:

Endianess applies to all integer types larger than one byte. I don't understand why you think endianess only applies to your 64 bit integer type but not to int... This seems to be the source of your confusion.

A major problem with your code is that unsigned int y = *y_p; is undefined behavior. What is the strict aliasing rule? So your program can't be assumed to have deterministic behavior.

If you want to actually print the bytes as stored in memory, you need to do so byte by byte:

for(size_t i=0; i<sizeof x; i  )
  printf("%.2X ", ((unsigned char*)&x)[i] );

This conversion is fine since character types are a special exception to strict aliasing. It prints 42 83 00 00 00 00 00 00 as expected.

Also you have minor a cosmetic issue here: 0x0000000000008342. Don't write leading zeroes like that thinking you've written a 64 bit integer constant. The type of this one is actually int (32 bit system) or unsigned int (8/16 bit system). The leading zeroes don't do a thing, you need to an append ull suffix. This isn't an issue in this particular snippet, but could become one if you bring this style into real programs.

CodePudding user response:

printf("%x\n", unsigned_number); will print the value of unsigned_number in hexadecimal just like printf("%u\n", unsigned_number); will print it in decimal.

Neither is concerned with the internal representation of unsigned_number. printf("%x",...) doesn't do a hexdump (unless of course you call it in a loop on every char of your data).

  • Related