yirufeng
247字小于1分钟
2024-05-13
package main
import (
"fmt"
)
type BitMap struct {
bits []byte
}
func NewBitMap(capacity int) BitMap {
return BitMap{make([]byte, (capacity+7)/8)}
}
func (bitmap *BitMap) Set(num int) {
if (num > 8*len(bitmap.bits)) {
return
}
pos := num / 8
offset := uint(num % 8)
bitmap.bits[pos] |= (0x80 >> offset)
}
func (bitmap *BitMap) Check(num int) bool {
if (num > 8*len(bitmap.bits)) {
return false
}
pos := num / 8
offset := uint(num % 8)
return bitmap.bits[pos] & (0x80 >> offset) > 0
}
func main() {
bitmap := NewBitMap(15)
bitmap.Set(2)
bitmap.Set(15)
bitmap.Set(30)
fmt.Println(bitmap.Check(2))
fmt.Println(bitmap.Check(3))
fmt.Println(bitmap.Check(15))
fmt.Println(bitmap.Check(30))
}