bit: fixed em
This commit is contained in:
parent
cdaad978da
commit
250b87e9c0
2 changed files with 62 additions and 0 deletions
31
bit/bit.go
31
bit/bit.go
|
@ -8,6 +8,25 @@ func (b *Bit) Flip() {
|
|||
|
||||
type Bits []Bit
|
||||
|
||||
func toBits(b byte) Bits {
|
||||
var o = make(Bits, 8)
|
||||
for bit, mask := 0, byte(128); bit < 8; bit, mask = bit+1, mask>>1 {
|
||||
if b&mask != 0 {
|
||||
o[bit] = 1
|
||||
}
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func NewBits(bytes []byte) Bits {
|
||||
var l = len(bytes)
|
||||
var o = make(Bits, 0)
|
||||
for i := 0; i < l; i++ {
|
||||
o = append(o, toBits(bytes[i])...)
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func (bits *Bits) Bytes() []byte {
|
||||
var l = len(*bits)
|
||||
var o = make([]byte, (l+7)/8)
|
||||
|
@ -18,3 +37,15 @@ func (bits *Bits) Bytes() []byte {
|
|||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func (bits *Bits) String() string {
|
||||
var s = ""
|
||||
for _, b := range *bits {
|
||||
if b == 0x01 {
|
||||
s += "1"
|
||||
} else {
|
||||
s += "0"
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
|
31
bit/bit_test.go
Normal file
31
bit/bit_test.go
Normal file
|
@ -0,0 +1,31 @@
|
|||
package bit
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestBit(t *testing.T) {
|
||||
var tests = []struct {
|
||||
Test []byte
|
||||
Want Bits
|
||||
}{
|
||||
{
|
||||
[]byte{0x2a},
|
||||
Bits{0, 0, 1, 0, 1, 0, 1, 0},
|
||||
},
|
||||
{
|
||||
[]byte{0xbe, 0xef},
|
||||
Bits{1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
got := NewBits(test.Test)
|
||||
if len(got) != len(test.Want) {
|
||||
t.Fatalf("expected length %d, got %d [%s]", len(test.Want), len(got), got.String())
|
||||
}
|
||||
for i, b := range got {
|
||||
if b != test.Want[i] {
|
||||
t.Fatalf("bit %d is off: %v != %v", i, got, test.Want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Reference in a new issue