-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitset.go
93 lines (62 loc) · 1.91 KB
/
bitset.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
90
91
92
93
/*
Package bitset implements a simple bitset using math/big
the motivation was that I needed a simple way to store
bitstrings as hex values that could easily work on the frontend
side of a web app with javascript. Since BitSet is composed of a big.Int
you can use methods like Int64 to get back a decimal representation of the bitset
Example use:
import "bitset"
b := bitset.New(0)
b = b.FromHexString("0f")
*/
package bitset
import (
"errors"
"fmt"
"math/big"
)
// type BitSet wraps a *big.Int
type BitSet struct {
*big.Int
}
// New(x int64) *BitSet given a int64 return a new bitset represented by this number
func New(x int64) *BitSet {
return &BitSet{big.NewInt(x)}
}
// FromHexString(hexstr string) error load a bitset into the existing bitset instance using a hexadecimal value
func (b *BitSet) FromHexString(hexstr string) error {
var ok bool
b.Int, ok = b.SetString(hexstr, 16)
if !ok {
return errors.New("cannot convert " + hexstr + " to hex value to big int")
}
return nil
}
// String() string implements Stringer interface returns the hex value of the bitset
func (b *BitSet) String() string {
return b.ToHexString()
}
// ToHexString() string returns the hex representation of the bit set
func (b *BitSet) ToHexString() string {
return fmt.Sprintf("%x", b.Bytes())
}
// ToInt() return int version if possible
func (b *BitSet) ToInt() int {
return int(b.Int64())
}
// Set(i int64) sets the corresponding set of bits by ORing the decimal value with the set
func (b *BitSet) Set(i int64) {
b.Int = b.Int.Or(b.Int, big.NewInt(i))
}
// SetBit(i int64) sets a single bit in the set
func (b *BitSet) SetBit(i int64) {
b.Int = b.Int.SetBit(b.Int, int(i), 1)
}
// UnSetBit(i int64) unsets a single bit in the set
func (b *BitSet) UnSetBit(i int64) {
b.Int = b.Int.SetBit(b.Int, int(i), 0)
}
// Get(i int) uint gets the bit value in the set
func (b *BitSet) Get(i int) uint {
return b.Int.Bit(i)
}