Why do casting a hex int to a char* prints it backwards?

Viewed 72

I thought I understood how memory works until I run this code, is memory backwards ? or I'm missing something ?

Code:

#include <stdio.h>
int main()
{
    int a = 0x12345678;

    char *c = (char *)&a;

    for (int i = 0; i < 4; i++)
    {
        printf("c[%d]=%x \n", i, *(c + i));
    }

    return 0;
}

Output:

c[0]=78

c[1]=56

c[2]=34

c[3]=12
2 Answers

What you have just done is demonstrate which "endian" your computer's architecture is using (i.e., your computer uses "little endian", not "big endian").

If your computer's architecture had instead been "big endian", then your output would instead have been this:

c[0] = 12
c[1] = 34
c[2] = 56
c[3] = 78

You may want to read this for more information: https://en.wikipedia.org/wiki/Endianness

It is because of the endianness of your machine. Check this article

A big-endian system stores the most significant byte of a word at the smallest memory address and the least significant byte at the largest. A little-endian system, in contrast, stores the least-significant byte at the smallest address.

Your machine is little-endian.

Related