How to create a custom bitset implementation in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// BitSet represents a set of bits using a slice of uint64.
// Each uint64 holds 64 bits, efficiently storing large bitsets.
type BitSet struct {
    data []uint64
}

// NewBitSet initializes a BitSet with the specified size.
// The array length is calculated based on the required number of 64-bit blocks.
func NewBitSet(size int) *BitSet {
    return &BitSet{
        data: make([]uint64, (size + 63) / 64), // Divide by 64 to determine required storage
    }
}

// Set sets the bit at the given position to 1.
func (b *BitSet) Set(pos int) {
    b.data[pos / 64] |= 1 << (pos % 64) // Uses bitwise OR to set the specific bit
}

// Clear sets the bit at the given position to 0.
func (b *BitSet) Clear(pos int) {
    b.data[pos / 64] &^= 1 << (pos % 64) // Uses bitwise AND NOT to clear the specific bit
}

// IsSet checks if the bit at the given position is set (returns true if it is).
func (b *BitSet) IsSet(pos int) bool {
    return b.data[pos / 64] & (1<<(pos % 64)) != 0 // Uses bitwise AND to check the bit value
}

func main() {
    // Create a BitSet with 128 bits
    bitset := NewBitSet(64)

    // Set bit at position 5
    bitset.Set(5)
    
    // Print the BitSet in binary format
    fmt.Printf("Bitset: %064b\n", bitset.data)

    // Check if bit at position 3 is set
    isSet := bitset.IsSet(5)
    fmt.Printf("Is bit 5 set? %v\n", isSet)

    // Clear bit at position 5
    bitset.Clear(5)

    // Check if the bit is still set after clearing
    fmt.Printf("Is bit 5 set after clearing? %v\n", bitset.IsSet(5))
    
    // Print the BitSet in binary format
    fmt.Printf("Bitset: %064b\n", bitset.data)
}

 
/*
run:
 
Bitset: [0000000000000000000000000000000000000000000000000000000000100000]
Is bit 5 set? true
Is bit 5 set after clearing? false
Bitset: [0000000000000000000000000000000000000000000000000000000000000000]

*/

 



answered May 7 by avibootz
...