4

I'm trying to cast a 115bit data to a union of bitfields and getting a wrong result.

Setup

I have two types of data:

Configuration: data[62:0]
               addr[113:107]
               type[114]

RawBits:       lowBits[63:0]
               highBits[115:64]

So I defined the following bitfields and union:

typedef struct RawBits {
  unsigned long int lowBits:64;
  unsigned long int highBits:51;
  unsigned long int reserved :13;
} __attribute__((packed))rawBits;

typedef struct Configuration {
  unsigned long int data : 62;
  unsigned long int addr : 7;
  unsigned long int type : 1;
  unsigned long int reserved : 58;
} __attribute__((packed))Configuration ;

typedef union Instruction {
  RawBits bits;
  Configuration configuration;
} __attribute__((packed))Instruction;

As data I used:

uint8_t configuration_test[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc,
                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfc, 0x00,

And to convert the buffer to the union type I used simple casting:

Instruction *instruction = (Instruction *)configuration_test;

Expected result

instruction->bits->lowBits  = 0xfffffffffffffffc
instruction->bits->highBits = 0x00000000000001fc
instruction->bits->reserved = 0x0000000000000000

instruction->configuration->data     = 0x3fffffffffffffff
instruction->configuration->addr     = 0x000000000000007f
instruction->configuration->type     = 0x0000000000000000
instruction->configuration->reserved = 0x0000000000000000

Real result

instruction->bits->lowBits  = 0xfcffffffffffffff
instruction->bits->highBits = 0x0004010000000000
instruction->bits->reserved = 0x000000000000001f

instruction->configuration->data     = 0x3cffffffffffffff
instruction->configuration->addr     = 0x0000000000000003
instruction->configuration->type     = 0x0000000000000000
instruction->configuration->reserved = 0x0003f00400000000

0 Answers0