Read 'N' bit from a byte

2019-08-10 22:25发布

问题:

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

回答1:

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


回答2:

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:

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:

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
}


回答5:

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


标签: c mplab