C data byte bit data setting

purpose

There are currently sixteen numbers that need to be stored, 1 | 0;
16 length, the first thing that comes to mind is two bytes, short type;

For example

The interface stores 32 check boxes, the background color is green, and after clicking the selection, it is red.
Insert picture description here
According to the selected check box, the storage state,
two ideas:

1 data structure

typedef union _SWITCHS
{
    
    
    struct _S
    {
    
    
        unsigned int switch_1 : 1 ;
        unsigned int switch_2 : 1 ;
        unsigned int switch_3 : 1 ;
        unsigned int switch_4 : 1 ;
        unsigned int switch_5 : 1 ;
        unsigned int switch_6 : 1 ;
        unsigned int switch_7 : 1 ;
        unsigned int switch_8 : 1 ;
        unsigned int switch_9 : 1 ;
        unsigned int switch_10 : 1 ;
        unsigned int switch_11 : 1 ;
        unsigned int switch_12 : 1 ;
        unsigned int switch_13 : 1 ;
        unsigned int switch_14 : 1 ;
        unsigned int switch_15 : 1 ;
        unsigned int switch_16 : 1 ;
    }S;
      unsigned char c[2];
      unsigned short int i;
}SWITCHS;


switch1.i = 0;	//初始化赋值为0
if(ui->checkBox_one_1->isChecked())
   {
    
    
       switch1.S.switch_1 = 1;
   }
   else
   {
    
    
       switch1.S.switch_1 = 0;
   }
.........//一次取值 23456...

Insert picture description here

2 or | operator

unsigned short int group1;
unsigned short int bitTab[16] = {
    
    0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0X100,0X200,0X400,0X800,0X1000,0X2000,0X4000,0X8000};

group1 = 0;		//初始化赋值为0

 if(ui->checkBox_group_1->isChecked())
 {
    
    
     group1 |= bitTab[0];
 }
................//依次取值 23456....

Insert picture description here
Both of the above methods are possible

Guess you like

Origin blog.csdn.net/qq_45646951/article/details/114741411