1

In a project of STM32, I came through a code like this :

typedef union {
    struct __attribute__ ((packed)){        
        uint8_t ModePin0 :1;                
        uint8_t ModePin1 :1;
        uint8_t ModePin2 :1;
        uint8_t ModePin3 :1;
    } dmxModeBytes;
    uint16_t dmxMode;
} dmxModeUnion;

So, my question is what is the meaning of :1 after ModePin0 variable and for similar variables? Is it related to memory alignment?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    This is some seriously sloppy code. Basically it guarantees nothing about the behavior of those struct members, it's non-standard, non-portable goo. – Lundin Oct 05 '22 at 10:04

1 Answers1

2

It is not an operator it is a declaration of a bit field. The number after the sign ':' specifies the number of bits (the width) in the bit field.

From the C Standard (6.7.2.1 Structure and union specifiers)

9 A member of a structure or union may have any complete object type other than a variably modified type.123) In addition, a member may be declared to consist of a specified number of bits (including a sign bit, if any). Such a member is called a bit-field; 124) its width is preceded by a colon.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • So, `uint8_t ModePin0 :1` means the `ModePin0` will contain only 1 bit? – Ahmad Yeaseen Khan Oct 05 '22 at 07:55
  • 1
    @AhmadYeaseenKhan You are right. It will contain one bit that can store two values: 0 and 1. – Vlad from Moscow Oct 05 '22 at 08:08
  • 1
    And the four `ModePinx` members are all part of the same `uint8_t`, so they cover the lower four bits of the struct (and the union). – Codo Oct 05 '22 at 08:09
  • 3
    Just remember that the _position_ and _order_ of the bit fields is _**implementation defined**_. Make sure you and your compiler agree on that. Never assume that bit N will match some bitfield’s N. – Dúthomhas Oct 05 '22 at 08:14