Search code examples
cbitavrledoperations

bit comparison in loop on AVRs


I'm learning about bit logic in C on AVRs and I have a problem.

I want to compare an "i" bit (from the right) from int8_t variable and if it is 1, then do the next instruction, but it doesn't work. Here's what I write:

if (variable & (1<<i)==(1<<i)) instruction;

In example for following data:

uint8_t dot=0101;
PORTC=1;
for (int i=0; i<4; i++)
{
    PORTB = fourDigit[i];
    if (dot & (1<<i)==(1<<i)) PORTB--;
    PORTC<<=1;
}

The dot (as it is connected to PB0) should illuminate on the first and third digit, but at present it lamps on every digit. What's the problem?

Thanks for your time.


Solution

  • It is done by bit masking. If you want to check whether or not an i'th bit of a is 1 you will do something like this:

    if (a & (1 << i))
    {
        // Do something
    }
    

    This way all of the bits of a except the i'th one will be ANDed with zeros, thus getting a value of zero. The i'th bit will be ANDed with 1, thus not changing it's value. So the if condition will be true in case the bit is not zero, and false otherwise.
    The comparison code you are presenting should work as well, but I suspect the dot variable is not containing the value you think it is containing. uint8_t dot=0101; makes it to be equal to 101 in octal base (due to the leading zero) or 65 in decimal. Not 101 in binary.