Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement BitSet with Go?

Tags:

go

I didn't find a BitSet package in Go, so I tried to implement it. I'd like to use a array of uint64 to store the bits.

I need the number of bits to allocate the uint64 array. With Java, I can define a constructor that takes an integer. While Go doesn't provide constructor, how can I properly initialize the BitSet 'object' when user call new()?

like image 248
Stephen Hsu Avatar asked Feb 22 '10 14:02

Stephen Hsu


1 Answers

Go's standard big.Int can be used as a bit set:

package main

import (
    "fmt"
    "math/big"
)

func main() {
    var bits big.Int
    for i := 1000; i < 2000; i++ {
        bits.SetBit(&bits, i, 1)
    }
    for i := 0; i < 10000; i++ {
        if bits.Bit(i) != 0 {
            fmt.Println(i)
        }
    }
}

https://play.golang.org/p/xbIK-boouqC

like image 141
Lassi Avatar answered Oct 05 '22 04:10

Lassi