0

I'm looking through some code that uses both bit fields and uint_t types, and I'm not sure why bit fields are used instead of the uint_t types in this context.

Here is the code that uses bitfields for context - it is a link-layer packet structure. The main takeaway I found was that bit fields are only used in structs, whereas the uint_t types are everywhere else in the code.

typedef struct PPPoEPacketStruct {
    struct ethhdr ethHdr;   /* Ethernet header */
    unsigned int vertype:8; /* PPPoE Version (high nibble) and Type (low nibble) (must both be 1) */
    unsigned int code:8;    /* PPPoE code */
    unsigned int session:16;    /* PPPoE session */
    unsigned int length:16; /* Payload length */
    unsigned char payload[ETH_JUMBO_LEN]; /* A bit of room to spare */
} PPPoEPacket;

Why is this the case?

  • 1
    Bit-fields may be used in this way because the author wants to lay out the bits in memory in a particular format, such as constructing a packet in the format of some network protocol. Doing so using bit-fields in a structure is implementation-dependent; it relies on specific features of alignment, padding, and bit-fields in the C implementation(s) it is designed for. – Eric Postpischil Nov 30 '21 at 00:13
  • 1
    @chux-ReinstateMonica padding can be added as well if you use fixed sizes types in the structs or unions. Not too much difference. You need to pack the struct anyway in this case. The problem is the order of bits. GCC is consistent and starts from LSB but standard leaves it to the implementation – 0___________ Nov 30 '21 at 00:13
  • How will a uint8_t suit your purposes if a particular portion of a signal is packed into less than 8 bits? There is no uint3_t. – Jim Rogers Nov 30 '21 at 00:18
  • @0___________ True, within a `struct`, `unit8_t` and `unsigned char x:8` may incur padding. Comment deleted. – chux - Reinstate Monica Nov 30 '21 at 00:33
  • IIRC, the address of member `unsigned int a:8;` is not allowed. Address of `uint8_t b;` is OK. – chux - Reinstate Monica Nov 30 '21 at 00:35

0 Answers0