Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does casting a char array to an int pointer and writing to it using the pointer make the data reversed?

I created some simple code to test casting a char array to int pointer. This works fine as I expected, but when I wrote to the array using the pointer, the data got swapped MSB<-->LSB when I print the c array back out. Why does this happen? Is this an OS dependent thing?

#include "stdio.h"

const int SIZE = 12;

int _tmain(int argc, _TCHAR * argv[]) {
    unsigned char c[SIZE] = {
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
    };
    unsigned int * ptr = (unsigned int * ) c;
    int i;

    printf("Int size=%d\n", sizeof(unsigned long));

    for (i = 0; i < sizeof(c); i++) {
        printf("%X, ", c[i]);
    }
    printf("\n\n");

    for (i = 0; i < sizeof(c) / sizeof(unsigned long); i++) { * ptr++ = i;
    }

    for (i = 0; i < sizeof(c); i++) {
        printf("%X, ", c[i]);
    }

    printf("\n");
    return 0;
}

Here is the output:

Int size=4
1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C,
0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0,
like image 681
ryeager Avatar asked May 22 '15 23:05

ryeager


2 Answers

Your architecture is Little Endian, which means the least significant byte is stored first in memory:

enter image description here

In your case 0x00000001 is written in the order [0x01, 0x00, 0x00, 0x00].

like image 156
Barry Avatar answered Oct 05 '22 22:10

Barry


This is caused by endianness of your CPU architecture. Your architecture seems to be little endian to cause this kind of inversions.

like image 29
Christophe Avatar answered Oct 06 '22 00:10

Christophe