Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping bits to int

Tags:

go

I'm trying to map a uint64 array bit positions to an int array (see below). BitSet is a []uint64. Below is my code as currently setup. But I am wondering if there could be a std function in golang that can reduce this code. Other language has BitArray or other objects that makes life much easier.

So, in golang, do we have to code this? is there a better to do this?

// Indexes the index positions of '1' bits as an int array
func (b BitSet) Indexes() []int {
    // set up masks for bit ANDing
    masks := make([]uint64, _BitsPerUint64)
    for i := 0; i < _BitsPerUint64; i++ {
        masks[i] = (1 << uint(i))
    }
    // iterate bitset
    indexes := make([]int, 0, len(b)*4)
    for i := 0; i < len(b); i++ {
        for m := 0; m < _BitsPerUint64; m++ {
            if masks[m]&b[i] > 0 {
                indexes = append(indexes, i*_BitsPerUint64+m)
            }
        }
    }
    return indexes
}
like image 941
Riyaz Mansoor Avatar asked Oct 27 '25 11:10

Riyaz Mansoor


1 Answers

func (b BitSet) Indexes() []int {
    retval := make([]int, 0, len(b)*64)
    for idx, value := range b {
        for i := 0; i < 64; i++ {
            if value & (1<<uint(i)) != 0 {
                retval = append(retval, idx*64 + i)
            }
        }
    }
    return retval
}

like image 77
Andrew W. Phillips Avatar answered Oct 29 '25 01:10

Andrew W. Phillips



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!