Ask Your Question
1

What is the way to incorporate BitSet in Go?

asked 2023-03-01 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-05-07 23:00:00 +0000

ladyg gravatar image

BitSet is not a standard package in Go, but it can be implemented using uint64 or uint32 data types and bit manipulation operations. Here is an example of how to implement a BitSet in Go:

type BitSet struct {
    bits []uint64
}

func NewBitSet(size int) *BitSet {
    if size < 1 {
        return nil
    }
    return &BitSet{
        bits: make([]uint64, (size+63)/64),
    }
}

func (bs *BitSet) Set(pos int) bool {
    if pos < 0 || pos >= len(bs.bits)*64 {
        return false
    }
    index, offset := pos/64, pos%64
    bs.bits[index] |= (1 << uint(offset))
    return true
}

func (bs *BitSet) Clear(pos int) bool {
    if pos < 0 || pos >= len(bs.bits)*64 {
        return false
    }
    index, offset := pos/64, pos%64
    bs.bits[index] &^= (1 << uint(offset))
    return true
}

func (bs *BitSet) Get(pos int) bool {
    if pos < 0 || pos >= len(bs.bits)*64 {
        return false
    }
    index, offset := pos/64, pos%64
    return (bs.bits[index] & (1 << uint(offset))) != 0
}

This implementation uses a slice of uint64 to store the bits and provides three methods Set(), Clear(), and Get() that manipulate the bits at a given position. The NewBitSet() function creates a new BitSet with the given size. The Set() method sets the bit at the given position to 1, the Clear() method clears the bit, and the Get() method returns the value of the bit.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-01 11:00:00 +0000

Seen: 13 times

Last updated: May 07 '22