From 250b87e9c0992d0ba6ca41d46d50d2eb712eeb57 Mon Sep 17 00:00:00 2001 From: Wijnand Modderman-Lenstra Date: Wed, 9 Dec 2015 00:39:44 +0100 Subject: [PATCH] bit: fixed em --- bit/bit.go | 31 +++++++++++++++++++++++++++++++ bit/bit_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 bit/bit_test.go diff --git a/bit/bit.go b/bit/bit.go index eef9f48..9b505d5 100644 --- a/bit/bit.go +++ b/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 +} diff --git a/bit/bit_test.go b/bit/bit_test.go new file mode 100644 index 0000000..cfdbace --- /dev/null +++ b/bit/bit_test.go @@ -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) + } + } + } +}