C语言利用联合体和结构体位域实现位带操作
C语言编程时经常需要操作特定的数据中特定的bit位,可以通过与、或操作实现。我试了一下用结构体位域和联合体,实现了可单独对bit操作。和正常变量赋值一样,即可对单独的bit位写1或写0。下面是代码和运行结果。
小白的第一篇博客,工作时遇到的问题用博客记录一下,方便以后查看。希望能坚持下去。
#include "stdio.h"
typedef struct
{
unsigned int b1:1;
unsigned int b2:1;
unsigned int b3:1;
unsigned int b4:1;
unsigned int b5:1;
unsigned int b6:1;
unsigned int b7:1;
unsigned int b8:1;
} _bit;
union bit_test
{
char byte;
_bit bit;
}test_a;
int main(void)
{
test_a.byte = 0x55;
printf("b1=%d,b2=%d,b3=%d,b4=%d\n",test_a.bit.b1,test_a.bit.b2,test_a.bit.b3,test_a.bit.b4);
test_a.bit.b2 = 1;
test_a.bit.b7 = 0;
printf("test_a=%d\n",test_a.byte);
return 0;
}