首页 > 编程语言 > 详细

C语言获取byte中的bit操作

时间:2021-06-21 20:14:51      阅读:21      评论:0      收藏:0      [点我收藏+]

想要获取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;
}

技术分享图片

C语言获取byte中的bit操作

原文:https://www.cnblogs.com/fll0601/p/14913809.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!