Understanding bitfield packing in C ++

I'm trying to understand beatbits. The following example is presented in C ++ online docs .

#include <iostream>
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: unused
unsigned char b1 : 3, : 2, b2 : 6, b3 : 2;
};
int main()
{
    std::cout << sizeof(S) << '\n'; // usually prints 2
}

What I do not understand in this example is that in the comments above the code says that after b1: 3 there are 2 unused bits. And then after b3: 2 there are 3 bits unused. Why? Shoudn 't which is the number of bits in unsigned char bits defined by type? Or the number of unauthorized bits remaining to the next boundary of the allocation unit?

+4
source share
3 answers

Packing all field declarations on one line makes it a little harder to understand what is going on. Here is the same, but reformatted:

struct S {
  unsigned char b1:3;  // 3 bits - b1
  unsigned char   :2;  // 2 bits - unused
  unsigned char b2:6;  // 6 bits - b2
  unsigned char b3:2;  // 2 bits - b3
                       // Total: 13 bits
};                     // 3 bits - unused (implicit padding)

"" : (1) b1 2 ; (2) 16 ( unsigned char).

+1

, . ++ " - ".

.

unsigned x : 3 ;

, . ,

unsigned x : 1 ;

32- ( ).

, . , :

1) , ; 2) - <, &, |, → .

+1

. :

#include <iostream>
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: unused
    unsigned char b1 : 3;
    unsigned char : 2; // How do you reference these?
    unsigned char b2 : 6, b3 : 2;
};
int main()
{
    std::cout << sizeof(S) << '\n'; // usually prints 2
}

http://ideone.com/6eCUB0

- , . , , - , - , .

, 16, 2 . , "" .

0

Source: https://habr.com/ru/post/1538672/


All Articles