From 6f468e70038b45c506a3d5f9b1e9b5c44ca3f195 Mon Sep 17 00:00:00 2001 From: rulk Date: Wed, 17 Jul 2019 20:42:26 +0300 Subject: [PATCH 1/2] added ability to export array as raw data --- bitarray.go | 20 ++++++++++++++++++++ bitarray_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/bitarray.go b/bitarray.go index be9ee8d..2a740ff 100644 --- a/bitarray.go +++ b/bitarray.go @@ -265,3 +265,23 @@ 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 +} 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) + } +} From 4f0771c465d34dadd35040a022b19f326bbef24b Mon Sep 17 00:00:00 2001 From: rulk Date: Tue, 23 Jul 2019 15:21:49 +0300 Subject: [PATCH 2/2] added public function to calculate required byte length --- bitarray.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/bitarray.go b/bitarray.go index 2a740ff..c754578 100644 --- a/bitarray.go +++ b/bitarray.go @@ -285,3 +285,8 @@ func FromByteArray(length int, data []byte) (*BitArray, error) { bytes: data, }, nil } + +func BitLenToByteLen(length int) int { + lenpad := nwords(length) * _BytesPW + return lenpad +}