m.lapeyre
m.lapeyre

Reputation: 486

Check if bit has toggled in C

I am working on bitwise manipulation (in C) and I wanted to know how to check if a bit has toggled between a previous value and the new value.

Example :
    oldValue = 0x0FF //0000 1111 1111 in binary
    newValue = 0x100 //0001 0000 0000 in binary

In this example I want to check if the bit8 (9th bit) has toggled from 0 to 1.

I know that if I want to know if a bit is set, is can use :

value & (1 << 8)

So, is this correct ? :

if( (oldValue & (1 << 8)) == (newValue & (1 << 8)) ) //return 0 if toggled

Upvotes: 2

Views: 1597

Answers (2)

thumbmunkeys
thumbmunkeys

Reputation: 20764

Use an XOR, it will be 1 for every bit that is different between oldValue and newValue:

   if((oldValue ^ newValue) == (1 << 7))
      // 8th bit has toggled

Upvotes: -2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

You can do it in two steps:

First, use XOR to find all bits that have toggled:

int allToggled = oldValue ^ newValue;

Then mask the bit that you want to keep - for example, by shifting allToggled to the right, so that the target bit is at position zero, and mask with 1:

int targetBitToggled = (allToggled >> 8) & 1;

Now combine these two expressions into a single condition:

if ((oldValue ^ newValue) & (1 << 8)) {
    // ... bit at position 8 has toggled
}

Note that instead of shifting the XOR-ed values right I shifted the bit mask left.

Upvotes: 6

Related Questions