aboutsummaryrefslogtreecommitdiff
path: root/bitfield/bitfield.go
blob: c469281567ce20f07b11fc5fc37c482d25e20ff0 (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
39
40
41
42
package bitfield

import "fmt"

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) {
		return (int(b[x]>>y) & 1) == 1
	}
	return false
}

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

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

func (b BitField) String() string {
	return fmt.Sprintf("% x", []byte(b))
}