获取某个数中某一位的二进制值

 1     int a1 = 1;//1
 2     int a2 = 2;//11
 3     int a3 = 4;//111
 4     int a4 = 8;//1111
 5     int a5 = 16;//11111
 6     int a6 = 32;//111111
 7     int a7 = 64;//1111111
 8     int a8 = 128;//11111111
 9 
10     int b1 = (a1 >> 0) & 0x01;
11     int b2 = (a2 >> 1) & 0x01;
12     int b3 = (a3 >> 2) & 0x01;
13     int b4 = (a4 >> 3) & 0x01;
14     int b5 = (a5 >> 4) & 0x01;
15     int b6 = (a6 >> 5) & 0x01;
16     int b7 = (a7 >> 6) & 0x01;
17     int b8 = (a8 >> 7) & 0x01;
18 
19     CString strMsg;
20     strMsg.Format(_T("%d %d %d %d %d %d %d %d"), b1, b2, b3, b4, b5, b6, b7, b8);
21     AfxMessageBox(strMsg);//1 1 1 1 1 1 1 1
1 int getBitValue(int iNumber, int iBit)
2 {
3     return (iNumber >> (iBit - 1)) & 1;
4 }

 

static byte SetbitValue(byte data, int index, bool flag)
{
    if (flag == 1)
    {
        data |= (1 << index);
    }
    else if (flag == 0)
    {
        data &= ~(1 << index);
    }

    return data;
}

 

取一个数的高低4位

char c = 0x61;
int high = c >> 4;
int low = c & 0x0F;

 

posted @ 2022-01-18 14:58  ckrgd  阅读(168)  评论(0编辑  收藏  举报