C语言获取byte中的bit操作

想要获取byte中某个bit值:

(val&(0x1<<n))>>n

#include <stdio.h>

int main(){

    unsigned char byte = 0x5D;  //二进制:‭01011101‬
    
    //单独第n位:
    //(val&(0x1<<n))>>n
    char c0 = (byte&(0x1<<0))>>0;
    char c1 = (byte&(0x1<<1))>>1;
    char c2 = (byte&(0x1<<2))>>2;
    char c3 = (byte&(0x1<<3))>>3;
    char c4 = (byte&(0x1<<4))>>4;

    printf("value bit0 = %d.\n",c0);
    printf("value bit1 = %d.\n",c1);
    printf("value bit2 = %d.\n",c2);
    printf("value bit3 = %d.\n",c3);
    printf("value bit4 = %d.\n",c4);

    return 0;
}

取出byte中的全部bit数:

#include <iostream>
#include <math.h>
using namespace std;

void test_01(){

    unsigned char c = 0x33;
    int b[8];
    for(int i =0; i<8; i++)
    {
        b[i] = ((c & (unsigned char)pow(2, i)) >> i);
        cout<<b[i]<<endl;
    }
}
void test_02(){

    unsigned char c = 0x33;
    int b[8];
    for(int i =0; i<8; i++)
    {
        b[i] = ((c >> i) & 1);
        cout<<b[i]<<endl;
    }
}
int main()
{
    // test_01();
    test_02();
    return 0;
}

posted @ 2021-06-21 15:47  方罗良  阅读(2574)  评论(0)    收藏  举报