Cheatography
https://cheatography.com
When dealing with software close to hardware, these bit hacks might come in handy. From setting and getting to parity and calculations.
This is a draft cheat sheet. It is a work in progress and is not finished yet.
C/C++ bitwise operations
& |
AND |
| |
OR |
^ |
XOR |
~ |
NOT |
<< |
SHIFT (left) |
>> |
SHIFT (right) |
Useful snippets
Counting (c) bits set in x for (c = 0; x; c++) { x &= vx- 1; }
|
Computing parity in parallel (32 Bit) x ^= x >> 16; x ^= x >> 8; x ^= x >> 4; x &= 0xf; return (0x6996 >> x) & 1;
|
|
|
Integer arithmetics
|
Multiply by n times 2 |
|
Divide by n times 2 |
|
Is x even? |
return (x && !(x & (x - 1)))
|
Is x power of 2? |
|
Has x opposite sign than y? |
|
min(x,y) |
|
max(x,y) |
|
|
Single bit operations
|
Set the nth bit |
|
Unset the nth bit |
|
Toggle the nth bit |
|
Test if the nth bit is set |
|
Turn off rightmost 1bit |
|
Isolate rightmost 1bit |
|
Right propagate rightmost 1bit (fill in ones) |
|
Turn on rightmost 0bit |
|
Isolate rightmost 0bit |
|