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;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM