How to reverse bitfield arrangement?

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

How to reverse bitfield arrangement?

2,430 Views
fangfq
Contributor III

Hi,

I have a structure that contains bitfields in code. The question is on how to change the arrangement order of the bitfields within the byte.

Instead of having it arranged from MSB  to LSB, (What S32 DS doing by default)

typedef struct

{

   uint8_t    a:4;

   uint8_t    b:3;

} test;

LSB    0    1    2    3    4    5    6    7    MSB

       none b0  b1  b2  a0  a1  a2  a3

I would like to make it arranged from LSB to MSB,

typedef struct

{

   uint8_t    a:4;

   uint8_t    b:3;

} test;

LSB    0    1    2    3    4    5    6    7    MSB

          a0  a1  a2  a3  b0  b1  b2 none

This issue caused very serious problems on CAN communication legacy code as all the signals are defined as bitfields. 

In CodeWarrior, there was an option to config the compiler:

#pragma reverse_bitfields on

http://www.nxp.com/docs/en/reference-manual/CCOMPILERRM.pdf  Page 192

I would like how to do the same settings in S32 DS. Thanks in advance!

0 Kudos
2 Replies

1,789 Views
alexanderfedoto
NXP Employee
NXP Employee

Bitfiled allocation is not detined by standard and compiler do whatever he wants with this. Although most of compilers doesn't change fields order inside of.

The simpliest way to support bi-endian is to use follwoing wrapper:

#ifdef LITTLE_ENDIAN /* Little endian order */
#define BITFIELDS_02(a01, a02) \
    a01; a02;
#elif defined BIG_ENDIAN
#define BITFIELDS_02(a01, a02) \
    a02; a01;

#else

#error "Endianess not defined"
#endif


typedef struct
{
BITFIELDS_02(
   uint8_t    a:4,
   uint8_t    b:3,
)
} test;

0 Kudos

1,789 Views
jiri_kral
NXP Employee
NXP Employee

Hello, 

I'm afraid that #pragma revese_bitfields on is no more supported by gcc version 4. There is similar question on stackoverflow site. 

Best way how to solve your issue is rewrite your structure definitions or do bit swap when you receive message from CAN bus. 

Jiri

0 Kudos