aboutsummaryrefslogtreecommitdiff
path: root/bitfield/bitfield.go
blob: 2346a2ceab741f834bc2a87b6b55b1e68ff66331 (plain)
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
package bitfield

type BitField []byte

func New(n int) BitField {
	l := n / 8
	if pad := (8 - n%8) % 8; pad != 0 {
		l++
	}
	return make(BitField, l)
}

func (b BitField) At(i int) bool {
	x := i / 8
	y := 7 - uint(i%8)
	if x < 0 || x > len(b) {
		panic("out of range")
	}
	return (int(b[x]>>y) & 1) == 1
}

func (b BitField) Set(i int) {
	x := i / 8
	y := 7 - uint(i%8)
	if x < 0 || x > len(b) {
		panic("out of range")
	}
	b[x] |= 1 << y
}

func (b BitField) Clear(i int) {
	x := i / 8
	y := 7 - uint(i%8)
	if x < 0 || x > len(b) {
		panic("out of range")
	}
	b[x] &= ^(1 << y)
}