BitMap

BitMap的golang实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package main

import "fmt"

type BitMap []uint64

func NewBitMap(nBits int) *BitMap {
bytesLength := ((nBits - 1) / 64 ) + 1
tmp := BitMap(make([]uint64, bytesLength, bytesLength))
return &tmp
}

func (this *BitMap) Set(k int) {
bytess := k / 64
bits := uint64(k % 64)
(*this)[bytess] |= uint64(0x01) << bits
}

func (this *BitMap) unset(k int) {
bytess := k / 64
bits := uint64(k % 64)
(*this)[bytess] |= ^(uint64(0x01) << bits)
}

func (this *BitMap) get(k int) bool {
bytess := k / 64
bits := uint64(k % 64)
return (*this)[bytess] & ( uint64(0x01) << bits) !=0
}

func main() {
bit:= NewBitMap(100)
bit.Set(10)
fmt.Println(bit.get(10))
fmt.Println(bit.get(11))
fmt.Println(bit.get(9))
bit.unset(10)
fmt.Println(bit.get(10))

}