This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

sizeof of struct with bit Field

please explain me why the sizeof (C51) returns 6 bytes for this struct instead of 5:

typedef struct DEKO_COMM_HEADER
{ UINT16 m_uiMsgOpcode;
UCHAR8 m_sblMsgPriority :2;
UINT16 m_sblDataLength :11;
UINT16 m_sblMsgTimeStamp :11;
}DEKO_COMM_HEADER, *PDEKO_COMM_HEADER;

UINT16 is typedef for unsigned int
UCHAR8 is typedef for unsigned char

thanks

Parents
  • I don't know how you expected to get the size 5.

    11+11+2 is 24 bits, but they can normally not be formed from 3 separate bytes, since a single byte can't store a bitfield with 11 bits. The compiler really want all fields for a bit field to be stored in the same byte/word/dword/xxx to allow all bits to be assignable with a single assign.

    The compiler may use a single 32-bit number for all bit fields (giving a total size of 6).

    The compiler may also allocate 2 16-bit numbers (one for each 11-bit value) and then decide to piggyback the 2-bit value into one of these 16-bit integers. This gives a total size of 6.

    The compiler may decide that the 2-bit field should not be piggybacked, thereby consuming 5 bytes for the bit fields, and 2 bytes for the opcode. For a 8-bit processor, this may result in a 7 byte large struct. A 16 or 32-bit processor would then have to pad the struct to make sure that an array of structs always places the 16-bit integer on an even address, i.e. making the struct 8 bytes large.

Reply
  • I don't know how you expected to get the size 5.

    11+11+2 is 24 bits, but they can normally not be formed from 3 separate bytes, since a single byte can't store a bitfield with 11 bits. The compiler really want all fields for a bit field to be stored in the same byte/word/dword/xxx to allow all bits to be assignable with a single assign.

    The compiler may use a single 32-bit number for all bit fields (giving a total size of 6).

    The compiler may also allocate 2 16-bit numbers (one for each 11-bit value) and then decide to piggyback the 2-bit value into one of these 16-bit integers. This gives a total size of 6.

    The compiler may decide that the 2-bit field should not be piggybacked, thereby consuming 5 bytes for the bit fields, and 2 bytes for the opcode. For a 8-bit processor, this may result in a 7 byte large struct. A 16 or 32-bit processor would then have to pad the struct to make sure that an array of structs always places the 16-bit integer on an even address, i.e. making the struct 8 bytes large.

Children
No data