Home > Enterprise >  How can I modify bit in position in Go?
How can I modify bit in position in Go?

Time:02-18

I tried to modify bit at a certain position, but ran into a problem. For example I have 1000000001, how can I modify it to 0000000001?

CodePudding user response:

You can apply a bitmask to only keep the bits you are interested in.

In this case if you only want the last bit, you apply the bitmask 0b0000000001

https://go.dev/play/p/RNQEcON7sw1

    // 'x' is your value
    x := 0b1000000001
    // Make the bitmask
    mask := 0b0000000001
    // Apply the bitmask with bitwise AND
    output := x&mask
    fmt.Println("This value == 1: ", output) 

Explaination

& is a bitwise operator for "AND". Which means it goes through both values bit by bit and sets the resulting bit to 1 if and only if both input bits are 1. I included a truth table for the AND operator below.

 ----------- ---------- -------------- 
| Input Bit | Mask Bit | Input & Mask |
 ----------- ---------- -------------- 
|         0 |        0 |            0 |
|         0 |        1 |            0 |
|         1 |        0 |            0 |
|         1 |        1 |            1 |
 ----------- ---------- -------------- 

Because my mask function only has a 1 in the last position, only the last position of the original input is kept. All preceding bits will always be 0.

CodePudding user response:

  1. Construct a mask that has a one in every place you want to manipulate
  2. Use bitwise OR to set bits.
  3. Use bitwise AND with the inverse mask to clear bits.
  4. Use XOR to toggle a bits
package main

import "fmt"

func main() {
    k := 3                      // manipulate the 3rd bit ...
    mask := uint8(1) << (k - 1) // ... using 0b00000100 as a mask

    var n uint8 = 0b10101010
    fmt.Printf("0bb\n", n) // 0b10101010

    // set kth bit
    n |= mask
    fmt.Printf("0bb\n", n) // 0b10101110

    // clear kth bit
    n &^= mask                // &^ is Go's AND NOT operator
    fmt.Printf("0bb\n", n) // 0b10101010

    // toggle kth bit
    n ^= mask
    fmt.Printf("0bb\n", n) // 0b10101110
}
  •  Tags:  
  • go
  • Related