diff --git a/bitarray.go b/bitarray.go index be9ee8d..c754578 100644 --- a/bitarray.go +++ b/bitarray.go @@ -265,3 +265,28 @@ func (bits *BitArray) ToArray() []int { return ints } + +func (bits *BitArray) ToByteArray() []byte { + return bits.bytes +} + +// New create a new BitArray with length(bits). +func FromByteArray(length int, data []byte) (*BitArray, error) { + if data == nil { + return nil, errors.New("data can't be nil") + } + lenpad := nwords(length) * _BytesPW + if len(data) != lenpad { + return nil, errors.New("length and size of data don't match") + } + return &BitArray{ + lenpad: lenpad, + length: length, + bytes: data, + }, nil +} + +func BitLenToByteLen(length int) int { + lenpad := nwords(length) * _BytesPW + return lenpad +} diff --git a/bitarray_test.go b/bitarray_test.go index d7cae30..a04c3cb 100644 --- a/bitarray_test.go +++ b/bitarray_test.go @@ -226,3 +226,27 @@ func TestLeq(t *testing.T) { _testLtOrEq(t, true) } + +func TestFromByteArray(t *testing.T) { + fmt.Println("Test: FromByteArray") + + _, e := FromByteArray(0, nil) + if e == nil { + t.Error("allowed nil data") + } + + bits := New(64) + data := bits.ToByteArray() + + recreatedData, e := FromByteArray(64, data) + + if e != nil || recreatedData == nil { + t.Error("failed to re-cteate byte array", e) + } + + recreatedData, e = FromByteArray(88, data) + + if e == nil || recreatedData != nil { + t.Error("failed to check for correct length", e) + } +}