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?

1
  • 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. Commented Oct 5, 2022 at 10:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So, uint8_t ModePin0 :1 means the ModePin0 will contain only 1 bit?
@AhmadYeaseenKhan You are right. It will contain one bit that can store two values: 0 and 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).
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.