示例代码:
#include "stdio.h"
#include "stdlib.h"
#include "stdint.h"
typedef union {
struct {
uint8_t b0 : 1; //lsb
uint8_t b1 : 1;
uint8_t b2 : 1;
uint8_t b3 : 1;
uint8_t b4 : 1;
uint8_t b5 : 1;
uint8_t b6 : 1;
uint8_t b7 : 1; //msb
}bit;
uint8_t value;
}switch_t;
int print_m(switch_t var);
int main(void)
{
switch_t sw1;
switch_t sw2;
//1 1 0 1 0 1 1 0
sw1.bit.b0 = 0;
sw1.bit.b1 = 1;
sw1.bit.b2 = 1;
sw1.bit.b3 = 0;
sw1.bit.b4 = 1;
sw1.bit.b5 = 0;
sw1.bit.b6 = 1;
sw1.bit.b7 = 1;
print_m(sw1);
sw2.value = 0xA3; //1 0 1 0 0 0 1 1
print_m(sw2);
return 0;
}
int print_m(switch_t var)
{
printf("------------\n");
printf("var=0x%02x\n", var.value);
printf("var.bit.b0=%d\n", var.bit.b0);
printf("var.bit.b1=%d\n", var.bit.b1);
printf("var.bit.b2=%d\n", var.bit.b2);
printf("var.bit.b3=%d\n", var.bit.b3);
printf("var.bit.b4=%d\n", var.bit.b4);
printf("var.bit.b5=%d\n", var.bit.b5);
printf("var.bit.b6=%d\n", var.bit.b6);
printf("var.bit.b7=%d\n", var.bit.b7);
return 0;
}
输出结果:
$ ./a.exe
------------
var=0xd6
var.bit.b0=0
var.bit.b1=1
var.bit.b2=1
var.bit.b3=0
var.bit.b4=1
var.bit.b5=0
var.bit.b6=1
var.bit.b7=1
------------
var=0xa3
var.bit.b0=1
var.bit.b1=1
var.bit.b2=0
var.bit.b3=0
var.bit.b4=0
var.bit.b5=1
var.bit.b6=0
var.bit.b7=1