C language bit field

Code:

#include<iostream>
using namespace std;

struct bf{
    int a:1;
    int b:3;
    int c:4;
}bit;

int main(){
    bit.a = 1;//一位空间仅有一个符号位所以输出为1
    cout << bit.a << endl;
    
    bit.b = 9;//9的二进制:1001,b分配的空间为3所以截断为:001
    cout << bit.b << endl;

    bit.c = 16;//16的二进制:10000,同上
    cout << bit.c << endl;

    bit.c = 9;//二进制:1001,被解释为-7
    cout << bit.c << endl;
    system("pause");
    return 0;
}

First, the internal struct will use the conventional method is not the same

struct bf{
    int a:1;
    int b:3;
    int c:4;
}bit;

The number after the colon represents the distribution of the number of bits

Published 21 original articles · won praise 36 · views 7241

Guess you like

Origin blog.csdn.net/weixin_44397852/article/details/100775667