Set and Clear Bits in Golang

Set and Clear Bits in Golang

There are bitwise operators in golang for bit manipulation. However, there is an unusual NOT operator. golang uses the ^ operator for NOT.

Code

NOT of a number

a := 101
notOfA := a ^ a // 101 ^ 101 = 010 

Setting a bit of a number

a := 101
b := 1 << 2 // second second bit
setBit := a | b // 101 | 010 = 111 

Clear a bit

a := 101
b := 1 << 2 // second second bit

// 101 & ^(010) => 101 & 101 => 101
setBit := a &^ b  

References

Written with StackEdit

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: