I love to see people writing Bit Twiddling code but I just can\'t understand it at all. Gone through Hacker\'s Delight and http://graphics.stanford.edu/~seander/bithacks.html, b
What is the easiest way to calculate the output of bits for example 1 | 2 = 3.
Write out the numbers as binary. This is how the numbers are really represented.
00000001
| 00000010
= 00000011
You're gonna have to study a little, but here's a little cheat sheet to know the number in binary form
128 | 64 | 32 | 16 | 8 | 4 | 2 | 1
If you want 3, go from left to right, filling up in the spaces that contains the values you need to create the number 3
128 | 64 | 32 | 16 | 8 | 4 | 2 | 1
X X
2 + 1 = 3 so you replace the ones marked with X
with 1
s and the rest with 0
s
00000011
The same for the number 2:
128 | 64 | 32 | 16 | 8 | 4 | 2 | 1
X
And the binary result is.
00000010
For the number 47:
128 | 64 | 32 | 16 | 8 | 4 | 2 | 1
X X X X X
Binary result:
00101111
This is not a rule, or formula or anything. It's just something to help you convert numbers a little faster, and practice it in your head. You'll still need to study a lot if you want to play with bits :-)