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