Assuming the following C code runs on a 32 bit platform (so sizeof(int) = 4), is the following code portable between big endian and little endian? When I ask "is it portable" I mean is the app going to print:
a) on a little endian platform
Address is 0xAABBCCDD
MSB is AA
LSB is DD
little endian
b) on a big endian platform
Address is 0xAABBCCDD
MSB is AA
LSB is DD
big endian
?
#include <stdio.h>
typedef unsigned char uint8;
typedef unsigned int uint32;
#define is_bigendian() ( (*(uint8*)&var) == 0 )
int main()
{
uint32 var = 1;
uint8 msb;
uint8 lsb;
printf("Address is %x\n", (uint32)&var);
msb = (((uint32)&var) & 0xFF000000) >> 24;
lsb = (((uint32)&var) & 0x000000FF) >> 0;
printf("MSB is %x\n", msb);
printf("LSB is %x\n", lsb);
if (is_bigendian())
{
printf("big endian\n");
}
else
{
printf("little endian\n");
}
return 0;
}
User contributions licensed under CC BY-SA 3.0