C51: Bit Field Unions Give Strange Results
Information in this article applies to:
When using a bit field structure in a union, values stored in the bit fields do not appear to be stored in the right place. For example:
stores the value 0x21436587 in u.var.
This is caused by the way the compiler stores bit fields. Bit fields are stored starting with the LSB. In this case, bit fields are stored in bytes (because the field type is unsigned char). So, the first byte in the union is filled with 1 (in the Least Significant 4 bits) and 2 (in the Most Significant 4 bits). The second byte in the union is filled with 3 (in the Least Significant 4 bits) and 4 (in the Most Significant 4 bits). And so on.
To store the nibbles in a different order, you must simply change the names of the bit fields. For example, changing the byte_nibbles structure definition to the following:
causes the above example to store the value 0x12345678 in u.var.
Changing the byte_nibbles structure definition to the following:
causes the above example to store the value 0x87654321 in u.var.
Last Reviewed: Thursday, February 25, 2021
of your data.