I have a union with an int and a char like so:
union {
int i;
char c[4];
} num;
When I set the int equal to 1, and print each char, I get this result:
1 0 0 0
...leading me to conclude that my machine is little endian. However, when I bit-shift left by 24, I get the following:
0 0 0 1
Swapping the endianness through a custom function (by swapping the left-most byte with the right, and same for the middle two), I end up with:
0 0 0 1
Left shifting this by 24 results in:
0 0 0 0
This leads me to conclude that the char[4] in my union is represented from right to left, in which case the endianness is actually the reverse of what's represented. But from my understanding, char arrays are generally interpreted from left to right, regardless of platforms. Are the char bytes in my union reversed?
Full code here:
#include <stdio.h>
#include <stdlib.h>
void endian_switch32(int *n)
{
int ret[4];
ret[0] = *n >> 24;
ret[1] = (*n >> 8) & (255 << 8);
ret[2] = (*n << 8) & (255 << 16);
ret[3] = *n << 24;
*n = ret[0] | ret[1] | ret[2] | ret[3];
}
int main (void) {
union {
int i;
char c[4];
} num;
num.i = 1;
printf("%d %d %d %d\n", num.c[0], num.c[1], num.c[2], num.c[3]);
num.i <<= 24;
printf("%d %d %d %d\n", num.c[0], num.c[1], num.c[2], num.c[3]);
num.i = 1;
printf("%d %d %d %d\n", num.c[0], num.c[1], num.c[2], num.c[3]);
endian_switch32(&num.i);
printf("%d %d %d %d\n", num.c[0], num.c[1], num.c[2], num.c[3]);
num.i <<= 24;
printf("%d %d %d %d\n", num.c[0], num.c[1], num.c[2], num.c[3]);
}
The result:
1 0 0 0
0 0 0 1
1 0 0 0
0 0 0 1
0 0 0 0