Bit hacks

Operators in C

&   -  bitwise and
|   -  bitwise or
^   -  bitwise xor
~   -  bitwise not
<<  -  bitwise shift left
>>  -  bitwise shift right

Bitwise Representation

The individual bits of 'x' are named b7, b6, b5, b4, b3, b3, b2, b1 and b0. 
b7 is the sign bit (the most significant bit), 
b0 is the least significant.

Check if the integer is even or odd

if x & 1
    its ODD
else
    its EVEN

For N-th bit1

Check n-th bit is set

x & (1 << n)

Set n-th bit to 1 or 0

x = x | (1 << n) //set
x = x ^ (x & (1 << n)) //unset 
x = x & ~(1 << n) //unset alternative

Toggle the n-th

x = x ^ (1<

Here is an example. Suppose you want to toggle 5th bit in value 01110101:

    01110101
^   00100000
    --------
    01010101

What about the same value but 5th bit originally 0?

    01010101
^   00100000
    --------
    01110101

For Rightmost bit

Set rightmost 1-bit (not LSB)

x = x & (x-1)

Get rightmost 1-bit (not LSB)

y = x & (-x)

Propagate the rightmost 1-bit

x = x | (x-1)

Set rightmost 0-bit

x = x | (x+1)

Get rightmost 0-bit

y = ~x & (x+1)

Sign check

1. Bit hacks

results matching ""

    No results matching ""