In a microcontroller project written in C, we defined the following macros to access different bytes of a multi byte variable (4 byte long):
#define BYTE_0(var) (*((unsigned char*) &var))
#define BYTE_1(var) (*(((unsigned char*) &var) + 1))
#define BYTE_2(var) (*(((unsigned char*) &var) + 2))
BYTE_0() accesses least significant byte, and so on. This is because we find that in case we need to access different bytes of a multi-byte variable separately (the micro in 8 bit), accessing the bytes using the code above produces fewer number of lines of code in assembly. As the code memory size is only 15K, few bytes are sometimes precious.
The micro we’re using is little-endian. I’m wondering if we port the code to another micro which is big-endian architecture, will the code above work? In other words, does C standard guarantee that (*((unsigned char*) &var)) will give the least significant byte of var?
Your macro does not work, it assumes little endian architecture. The C standard guarantees nothing in the case of your code. Endian-independent code is typically written with bit-wise operators, because they behave the same way no matter where the ls byte is allocated.
some_long & 0xFFis guaranteed by the C standard to give you the ls byte no matter endianess, while(uint8_t*)&some_longis endian-dependent.This link answers your question in detail: http://www.ibm.com/developerworks/aix/library/au-endianc/
Do a macro similar to the one in listing 12 with bitwise shift and bitwise AND, and it will be portable.