When creating a union of an unsigned integer and a 4 byte array in c, the order of the bytes seem to be reversed. Why is this?
For an integer with binary representation 10000000 00000000 00000000 00000000, I would expect b[0] = 10000000, b[1] = 00000000 etc..
#include <stdio.h>
#include <stdlib.h>
typedef union intByteRep{
unsigned int i; // 00000000 00000000 00000000 00000000
unsigned char b[4]; // b[0] b[1] b[2] b[3] - What we would expect
// b[3] b[2] b[1] b[0] - What is happening
} intByteRep;
char *binbin(int n);
int main(int argc, char **argv) {
intByteRep ibr;
ibr.i = 2147483648; // 10000000 00000000 00000000 00000000
for(int i = 0; i < 4; i++){
printf("%s ", binbin(ibr.b[i]));
}
printf("\n"); // prints 00000000 00000000 00000000 10000000
for(int i = 3; i >= 0; i--){
printf("%s ", binbin(ibr.b[i]));
}
printf("\n"); // prints 10000000 00000000 00000000 00000000
return 0;
}
/*function to convert byte value to binary string representation*/
char *binbin(int n)
{
static char bin[9];
int x;
for(x=0; x<8; x++)
{
bin[x] = n & 0x80 ? '1' : '0';
n <<= 1;
}
bin[x] = ' ';
return(bin);
}