aboutsummaryrefslogtreecommitdiff
path: root/ber
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2015-07-14 14:59:58 +0200
committerDimitri Sokolyuk <demon@dim13.org>2015-07-14 14:59:58 +0200
commit2e3613a9203ae2dccf6d09032a9edca22b5f5381 (patch)
treed2925ffa494ce9343ef86ac988097f0cedf75d2d /ber
parentb1def9e9ac3d610541f7ac4804947e7b872e9106 (diff)
Add BitString marshal
Diffstat (limited to 'ber')
-rw-r--r--ber/bits.go18
-rw-r--r--ber/bits_test.go15
2 files changed, 29 insertions, 4 deletions
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)
}
}
}