The following sets byte
to 1 on big-endian and 0 on little-endian.
uint16_t word = 0x0001;
uint8_t byte = *(((uint8_t *)&word) + 1);
Is there any way to get the address of the low or high byte that is cross-platform safe?
The following sets byte
to 1 on big-endian and 0 on little-endian.
uint16_t word = 0x0001;
uint8_t byte = *(((uint8_t *)&word) + 1);
Is there any way to get the address of the low or high byte that is cross-platform safe?
Maybe like this:
int isBigEndian()
{
uint16_t word = 0x0001;
return *(((uint8_t *)&word) + 1);
}
void main()
{
uint16_t word = 0x0001;
uint8_t byte = *(((uint8_t *)&word) + isBigEndian());
printf("%d\n", byte);
}
To avoid checking at run time everytime, you can use a #define
and verify it is a correct assumption using assert
. Like this:
#define BIG_ENDIAN 0 // 0 or 1 depending on what the platform is
void main()
{
assert(isBigEndian() == BIG_ENDIAN); // Make sure #define is OK
// more code...
}
Elsewhere in the code, you use the symbol BIG_ENDIAN
to compile code depending on the platform. So there is no other actual check than the assert
.
Since C99, code could use a compound literal to find the MSByte address offset.
Let the compiler form efficient code.
Below uses a 4-byte example to help illustrate adherence with big, little and PDP endian.
Example output (little endian)
For
uint16_t