Read 'N' bit from a byte

2019-08-10 22:11发布

I need to read a specific bit from a byte. The value i want to test is 0 or 1.

unsigned char Buffer[0]=2; 
//or binary 0b00000010

How can i read n bit from buffer. If it's 0 or 1? Example if 7 bit from byte is 0 or 1

标签: c mplab
5条回答
Lonely孤独者°
2楼-- · 2019-08-10 22:40

To check a bit if its 0 or 1, you can define a simple macro like:

#define BIT_ISSET(var, pos) (!!((var) & (1ULL<<(pos))))

and then use it in if-clauses.

Note the '!!' operator, to ensure that it returns 0 or 1.

查看更多
神经病院院长
3楼-- · 2019-08-10 22:40

To answer your question: which will check the value of 7th bit.

unsigned char Buffer = 2; //Hope this is what you are looking for 

if (((Buffer >> 7) & 0x01) == 1 )
{
    printf(" Bit is 1 ");
} 
else
{
    printf(" Bit is 0 ");
}

Similar way if you need to check the value of nth bit, replace 7 in if condition with n.

查看更多
神经病院院长
4楼-- · 2019-08-10 22:45

You can just use this function to pass your char and N(number of bit).The function will invoke a bitwise AND filtering out the bit you need to check.

bool check_N_bit(char a_char , int N)
{
    if (N>8)
    {
        return false;
    }
    if ((a_char&(0x01 << N-1)) > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
查看更多
孤傲高冷的网名
5楼-- · 2019-08-10 22:48

Of course you had to define your bit position in advance.

e.g.
Bit7 (MSB)
Bit0 (LSB)

Test for bit 7:

if (Buffer[0] & 0x80)
{
    //do action for bit 7 = 1
}
else
{
    // do action for bit7 = 0
}
查看更多
smile是对你的礼貌
6楼-- · 2019-08-10 22:57

You must define precisely how you count the bits:

  • starting at 0 or 1
  • from least significant to most significant or the other way?

Assuming bit 0 is the least significant, you can get bit 7 with this expression:

int bit7 = ((unsigned char)Buffer[0] >> 7) & 1;

Here is a generic loop:

for (int i = 7; i >= 0; i--) {
    putchar('0' + (((unsigned char)Buffer[0] >> i) & 1));
}
查看更多
登录 后发表回答