How to clear bits in the given range in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// Print bits of a 32-bit integer
func printBits(x uint32, label string) {
    // Print as 32-bit binary with leading zeros
    fmt.Printf("%s: %032b\n", label, x)
}

// Clear bits in range [l, r] inclusive (0 = least significant bit)
func clearBits(x uint32, l, r int) uint32 {
    if l < 0 || r > 31 || l > r {
        panic("Invalid bit range")
    }

    // maskLeft:
    // Create a mask with 1s above bit r and 0s from bit r down to 0.
    // Example: r = 5 → maskLeft = 11111111 11111111 11111111 11000000
    maskLeft := ^uint32(0) << (r + 1)
    printBits(maskLeft, "maskLeft ")

    // maskRight:
    // Create a mask with 1s below bit l and 0s from bit l upward.
    // Example: l = 3 → maskRight = 00000000 00000000 00000000 00000111
    maskRight := (uint32(1) << l) - 1
    printBits(maskRight, "maskRight")

    // Combine both masks:
    // maskLeft keeps bits above r.
    // maskRight keeps bits below l.
    // The range [l, r] becomes 0s.
    mask := maskLeft | maskRight
    printBits(mask, "mask     ")

    return x & mask
}

func main() {
    value := uint32(0b11111100111111001111110011111100)

    l := 3  // start bit
    r := 10 // end bit

    result := clearBits(value, l, r)

    printBits(value, "Before   ")
    printBits(result, "After    ")
}




/*
run:

maskLeft : 11111111111111111111100000000000
maskRight: 00000000000000000000000000000111
mask     : 11111111111111111111100000000111
Before   : 11111100111111001111110011111100
After    : 11111100111111001111100000000100

*/

 



answered Dec 30, 2025 by avibootz
...