Bit-Fields not working - CW10.2 - K10

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Bit-Fields not working - CW10.2 - K10

295 Views
ignisuti
Contributor IV

I have the following union in my code. The intent was that the incoming data packet could be stuffed into WEB_MSG__config_unit.data and then each piece of the packet could be individually extracted using something like this WEB_MSG__config_unit.param.UNIT_INFO__FIRMWARE_VERSION.

 

 

union    {    struct { u8  MESSAGE_CODE : 8; u8  MESSAGE_LENGTH : 8; u8  PACKET_NUMBER : 8; u16 UNIT_INFO__FIRMWARE_VERSION : 16; u32 UNIT_INFO__TIMESTAMP : 32; ... u8  CHECKSUM : 8; } param;    u8 data[64];     } WEB_MSG__config_unit; 

 

If I fill the WEB_MSG__config_unit.data with values 1 through 10, like this...

 

data

 

WEB_MSG__config_unit.param shows up like this...

 

param

 

I would expect UNIT_INFO__FIRMWARE_VERSION to be 0x403, but it appears that the 4th byte (value 0x03) is skipped so that the 16-bit UNIT_INFO__FIRMWARE_VERSION value can start at a new byte boundary.

 

How can I fix this to work the way I want?

Labels (1)
0 Kudos
1 Reply

191 Views
kef
Specialist I

Most likely UNIT_INFO__FIRMWARE_VERSION is word aligne, relative to the start of param struct. C compiler is allowed to do that to improve performance. Also some architectures may not allow word accesses to misaligned address, and even restart when this happens.

1) The best would be to make code portable and not rely on struct packing.

2) add padding byte between .._NUMBER and .._VERSION fields

3) Check compiler manual, maybe it is possible to turn off word alignment ir change struct packing rules. (I'm not familiar with Kinetis).

0 Kudos