Setting a Bit (OR)

result |= 1 << bit;

Bit-shift a 1 by the number of the bit you want to set and then or-equal it with the result. For example we will set the 4th bit.

result =

0

0

0

0

0

0

0

0

1<<4 =

0

0

0

0

1

0

0

0

|=

|=

|=

|=

|=

|=

|=

|=

result =

0

0

0

0

1

0

0

0

This maintains the original bit pattern of result as we see in this example.

result =

1

1

0

0

0

0

1

0

1<<4 =

0

0

0

0

1

0

0

0

|=

|=

|=

|=

|=

|=

|=

|=

result =

1

1

0

0

1

0

1

0

Clearing a Bit (AND NOT)

result &= ~(1 << bit);

We’ll continue the previous example by unsetting the 4th bit of the previous result.

result =

1

1

0

0

1

0

1

0

~1<<4 =

1

1

1

1

0

1

1

1

&=~

&=~

&=~

&=~

&=~

&=~

&=~

&=~

result =

1

1

0

0

0

0

1

0

Toggling a Bit (XOR)

result ^= 1 << bit;

We’ll continue the previous example by toggling the 4th bit of the previous result.

result =

1

1

0

0

0

0

1

0

1<<4 =

0

0

0

0

1

0

0

0

^=

^=

^=

^=

^=

^=

^=

^=

result =

1

1

0

0

1

0

1

0

Checking a Bit (AND)

result = (x >> (bit-1)) & 1;

We’ll check the 4th bit in the previous result.

x =

1

1

0

0

1

0

1

0

x>>3 =

0

0

0

1

1

0

0

1

&

&

&

&

&

&

&

&

1=

0

0

0

0

0

0

0

1

result =

0

0

0

0

0

0

0

1