Chp5: Bit Manipulation

Bits Facts and Tricks

x ^ 0s =  x

x & 0s =  0

x | 0s = x

x ^ 1s = ~x

x & 1s = x

x | 1s = 1s

x ^ x = 0

x & x = x

x | x = x

 

Common Bit Tasks:  Get, Set, Clear And Update

Get:  num & (1 << i) != 0

Set: num | (1 << i)

Clear:

clear ith bit: num & (~(1 << i))

clear all bits from the most significant bit through i: num & ((1 << i) - 1)

clear all bits from i though 0: num & (~((1 << (i + 1)) - 1))

Update: (num & (~(1 << i))) | (v << i)

5.4 

1 ((n & (n - 1)) == 0) //check if n is a power of 2 (or if n is 0)

5.5 Swap odd and even bits in an integer with as few instructions ad possible.

1 //0xaaaaaa is 1010101010 which mask all odd bits

2 public int swapOddEven(int x){

3     return ( ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1) );

4 }

 

你可能感兴趣的:(bit)