Monday, June 29, 2015

Bit Operation Review


And (&):

0 & 0 = 0

1 & 0 = 0

0 & 1 = 0

1 & 1 = 1

Or (|):

0 | 0 = 0

1 | 0 = 1

0 | 1 = 1

1 | 1 = 1

Xor (^):

0 ^ 0 = 0

1 ^ 0 = 1

0 ^ 1 = 1

1 ^ 1 = 0



Left Shift:

 x << y means x shifted y bits to the left. If you start shifting and you run out of space, the bits just “drop off”. For example:
00011001 << 2 = 01100100
00011001 << 4 = 10010000


Right Shit
x >> y means x shifted y bits to the right. If you start shifting and you run out of space, the bits just “drop off” the end. Example:
00011001 >> 2 = 00000110
00011001 >> 4 = 00000001

((n & (n-1)) == 0) checks if n is a power of 2 (or 0).



XOR
one number, when XOR with another number twice, it turns back to itself again.
e.g. 1000^0101=1101, 1101^0101=1000 that is a^b and ^b again to get back a. similarly, a^b and ^a again to get b. with this feature, you can swap two number by using XOR operations
a=a^b;
b=a^b;//b now is a
a=a^b;//this equivalent to a^b^a=b
(XOR with same number twice equals not applying anything)


 

No comments: