How to check whether only 2 bits in a number at a specific position are on (edge‑case‑safe) with Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func printBits(value uint64, width int) {
    for i := width - 1; i >= 0; i-- {
        mask := uint64(1) << uint(i)
        if value&mask != 0 {
            fmt.Print("1")
        } else {
            fmt.Print("0")
        }
    }
}

func exactBitSet(pos1, pos2 int, value uint64) bool {
    if pos1 < 0 || pos2 < 0 || pos1 >= 64 || pos2 >= 64 {
        return false
    }
    if pos1 == pos2 {
        return false
    }

    mask := (uint64(1) << uint(pos1)) | (uint64(1) << uint(pos2))
    return value == mask
}

func main() {
    tests := []struct {
        value uint64
        x, y  int
        width int
    }{
        {0b1000010000, 4, 9, 10},
        {0b0010000010, 1, 7, 10},
        {0b0000100100, 2, 5, 10},
        {0b1000010000, 3, 9, 10},
        {0b1001010000, 4, 9, 10},
        {0b1111111111, 4, 9, 10},
        {0b0000000000, 4, 9, 10},
        {0b1000010000, 4, 8, 10},
        {1, 0, 0, 1},
        {1, 0, 1, 1},
        {0, 1, 1, 1},
    }

    for _, t := range tests {
        printBits(t.value, t.width)
        fmt.Printf("  bits(%d, %d)  ->  %v\n",
            t.x, t.y, exactBitSet(t.x, t.y, t.value))
    }
}



/*
OUTPUT:

1000010000  bits(4, 9)  ->  true
0010000010  bits(1, 7)  ->  true
0000100100  bits(2, 5)  ->  true
1000010000  bits(3, 9)  ->  false
1001010000  bits(4, 9)  ->  false
1111111111  bits(4, 9)  ->  false
0000000000  bits(4, 9)  ->  false
1000010000  bits(4, 8)  ->  false
1  bits(0, 0)  ->  false
1  bits(0, 1)  ->  false
0  bits(1, 1)  ->  false
   
*/

 



answered Apr 3 by avibootz

Related questions

...