Weird endianness related bug
So, apparently when casting an array of bytes, C automatically reverses the endianness:
Code:
#include <stdio.h>
#include <stdint.h>
int main(){
uint8_t a[4] = {0x52,0x4a,0x75,0xd8};
uint32_t x = *(uint32_t*)a;
uint32_t y = 0x524a75d8;
printf("x=%x, y=%x, a=%02x%02x%02x%02x\n",x,y,a[0],a[1],a[2],a[3]);
}
It outputs x=d8754a52, y=524a75d8, a=524a75d8, which means the bytes (but not the bits!) of x are reversed with respect to y.
1. Why does this happen automatically?
2. How to make it not happen?
3. Why is endiannes split into bits and bytes, and the order is big bit, small byte?
For those wondering, I am using GCC 11.1.0 without any extra options.