Questions
- “:” (colon) in C/C++ struct, what does it mean?
- What does C++ struct syntax “a : b” mean?
- What does :1 and :8 mean?
Example #1
https://en.wikipedia.org/wiki/Bit_field
struct BoxProps
{unsigned int opaque : 1;unsigned int fill_color : 3;unsigned int : 4; // fill to 8 bitsunsigned int show_border : 1;unsigned int border_color : 3;unsigned int border_style : 2;unsigned char : 0; // fill to nearest byte (16 bits)unsigned char width : 4, // Split a byte into 2 fields of 4 bitsheight : 4;
};
Example #2
https://en.wikipedia.org/wiki/C_syntax#Bit_fields
struct f {unsigned int flag : 1; /* a bit flag: can either be on (1) or off (0) */signed int num : 4; /* a signed 4-bit field; range -7...7 or -8...7 */signed int : 3; /* 3 bits of padding to round out to 8 bits */
} g;
Example #3
https://en.cppreference.com/w/cpp/language/bit_field
struct S
{// will usually occupy 2 bytes:// 3 bits: value of b1// 2 bits: unused// 6 bits: value of b2// 2 bits: value of b3// 3 bits: unusedunsigned char b1 : 3, : 2, b2 : 6, b3 : 2;
};
Example #4
https://learn.microsoft.com/en-us/cpp/cpp/cpp-bit-fields?view=msvc-170
// bit_fields1.cpp
// compile with: /LD
struct Date {unsigned short nWeekDay : 3; // 0..7 (3 bits)unsigned short nMonthDay : 6; // 0..31 (6 bits)unsigned short nMonth : 5; // 0..12 (5 bits)unsigned short nYear : 8; // 0..100 (8 bits)
};
Example #5: union bit fields & uint8
https://stackoverflow.com/questions/36255992/union-bit-fields
union {
uint8_t raw;
struct {uint8_t a : 1;uint8_t b : 2;uint8_t padding : 5;
};
} U;