Search code examples
clinuxgccendianness

Program is Big-Endian even though system is Little-Endian


Somehow, my program is treating variables as big endian, even though my system is little endian.

When I execute "lscpu | grep Endian", it returns

Byte Order:                      Little Endian

But when I run a debug gcc (x86_64 linux) executable with following code:

int x = 1235213421;
printf("%x", x);

It returns 0x499FDC6D, while for little endian it should return 0x6DDC9F49


Solution

  • You told printf to print an integer so it does so according to the endianess, making the code portable. If you wish to view how the data is stored in memory, you have to do it byte by byte, like this:

    int x = 1235213421;
    unsigned char* ptr = (unsigned char*)&x;
    for(size_t i=0; i<sizeof(int); i++)
    {
      printf("%.2x", ptr[i]);
    }