-
Notifications
You must be signed in to change notification settings - Fork 4
/
bitvector_8.go
89 lines (75 loc) · 1.31 KB
/
bitvector_8.go
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package bitvector
import (
"fmt"
"math"
)
// Len8 is a 8-bit vector
type Len8 uint8
func (bv Len8) String() string {
return fmt.Sprintf("%08b", bv)
}
// Clear bits from index i (included) to index j (excluded)
func (bv Len8) Clear(i, j uint8) Len8 {
if i > j {
return bv
}
return (math.MaxUint8<<j | ((1 << i) - 1)) & bv
}
// Count the number of bits set to 1
func (bv Len8) Count() uint8 {
var count uint8
var index Len8 = 1
var i uint8
for {
if bv&index != 0 {
count++
}
index <<= 1
i++
if i == 8 {
break
}
}
return count
}
// Toggle ith bit
func (bv Len8) Toggle(i uint8) Len8 {
return bv ^ 1<<i
}
// Get ith bit
func (bv Len8) Get(i uint8) bool {
return (bv & (1 << i)) != 0
}
// Set ith bit
func (bv Len8) Set(i uint8, b bool) Len8 {
var value Len8
if b {
value = 1
}
var mask Len8 = ^(1 << i)
return (bv & mask) | (value << i)
}
// And operator
func (bv Len8) And(bv2 Len8) Len8 {
return bv & bv2
}
// Or operator
func (bv Len8) Or(bv2 Len8) Len8 {
return bv | bv2
}
// Xor operator
func (bv Len8) Xor(bv2 Len8) Len8 {
return bv ^ bv2
}
// AndNot operator
func (bv Len8) AndNot(bv2 Len8) Len8 {
return bv &^ bv2
}
// Push left shifts the bits
func (bv Len8) Push(i uint8) Len8 {
return bv << i
}
// Pop right shifts the bits
func (bv Len8) Pop(i uint8) Len8 {
return bv >> i
}