From 2e3613a9203ae2dccf6d09032a9edca22b5f5381 Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Tue, 14 Jul 2015 14:59:58 +0200 Subject: Add BitString marshal --- ber/bits.go | 18 ++++++++++++++++++ ber/bits_test.go | 15 +++++++++++---- 2 files changed, 29 insertions(+), 4 deletions(-) (limited to 'ber') diff --git a/ber/bits.go b/ber/bits.go index 8895e92..180228d 100644 --- a/ber/bits.go +++ b/ber/bits.go @@ -15,6 +15,24 @@ func UnmarshalBitString(b []byte) (bs Bits) { return } +func MarshalBitString(bs Bits) (b []byte) { + padding := (8 - len(bs)%8) % 8 + length := len(bs) / 8 + if padding != 0 { + length++ + } + b = make([]byte, length+1) + b[0] = byte(padding) + for i, bi := range bs { + x := 1 + i/8 + y := 7 - uint(i%8) + if bi { + b[x] |= 1 << y + } + } + return +} + func (bs Bits) String() (s string) { bmap := map[bool]string{ true: "1", diff --git a/ber/bits_test.go b/ber/bits_test.go index ebc8796..c20b3db 100644 --- a/ber/bits_test.go +++ b/ber/bits_test.go @@ -1,6 +1,9 @@ package ber -import "testing" +import ( + "bytes" + "testing" +) type bitTest struct { bytes []byte @@ -39,9 +42,13 @@ func bitsEqual(a, b Bits) bool { func TestBits(t *testing.T) { for _, test := range bitTestData { - bits := UnmarshalBitString(test.bytes) - if !bitsEqual(bits, test.bits) { - t.Error(test.bytes, "expexted", test.bits, "got", bits) + bi := UnmarshalBitString(test.bytes) + if !bitsEqual(bi, test.bits) { + t.Error(test.bytes, "expexted", test.bits, "got", bi) + } + by := MarshalBitString(test.bits) + if !bytes.Equal(by, test.bytes) { + t.Error(test.bits, "expexted", test.bytes, "got", by) } } } -- cgit v1.2.3