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 }

 

相关文章:

  • 2022-12-23
  • 2021-05-26
  • 2022-12-23
  • 2021-11-29
  • 2022-12-23
  • 2022-12-23
  • 2021-12-26
  • 2021-05-27
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-23
  • 2021-11-23
  • 2021-10-18
  • 2021-08-25
  • 2022-12-23
相关资源
相似解决方案