1. 程式人生 > >Bit manipulation in Go

Bit manipulation in Go

Bit manipulation is important to know when doing data compression, cryptography and optimization.

Bitwise operations include AND, NOT, OR, XOR and bit shifts.

Go supported bit operations include:

& AND
| OR
^ XOR
&^ AND NOT
<< left-shift
>> right-shift

Go does not have a dedicated NOT operator like C++ or Python. Instead we have to use the XOR operator to toggle the bits.

 var n byte = 0x0F
 fmt.Printf("%08b\n", n)
 n = ^n
 fmt.Printf("%08b\n", n)

This is the output:

00001111
11110000

Here are some common bit manipulation algorithms that can be done in Go

  • Swapping integers using XOR since XOR will result in 1 only if both bits are the same.
func swap(a, b int) (int, int) { 
 a = a ^ b 
 b = b ^ a 
 a = a ^ b 
 return a, b
}
  • Toggle bits using XOR
func flip(a int) int{
 a ^= 0xFFFFFFFF
 return a
}
  • Find Odd/even using AND
func isEven(n int) bool{
 if n&1 == 1 { 
  return false 
 } 
 return true
}
  • Find if a number is power of 2
func isPowerofTwo(n int) bool{
 if (n & (n-1) == 0){
  return true
 }
 return false
}

Like this:

Like Loading...