Golang

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 incluse:

& 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
}

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s