Menu Close

Go – How to set and unset a single bit in Go

Here, we will learn how to set and unset a single bit in Go. We will learn it by programming and using bitwise operators in go lang.

&^” aka “AND NOT” bitwise operator is used to unset a bit whereas “|” aka “OR” bitwise operator is used to set the bit.

Example:

1:) a = 1010

You want to unset bit at 2nd position 
from right side.

a = a &^ (1 << 1)

a = 8 which is equivalent to (1000)

2:) a = 1010

You want to set bit at 3rd position
from right side.

a = a | (1 << 2)

a = 14 which is equivalent to (1110)

Code:

package main

import (

 "fmt"

)

func main() {

  a := 10

  a = a &^ (1 << 1)

  fmt.Println(a)

  a = 10

  a = a | (1 << 2)

  fmt.Println(a)

}

Output:

8

14

To learn more about golang. Please follow given below link.

https://www.techieindoor.com/go-lang/

References:

https://golang.org/doc/
https://golang.org/pkg/

Posted in golang, Miscellaneous, operator

Leave a Reply

Your email address will not be published.