From c5b32db26a2dc043bf0777f9f9532e4c360241b2 Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Fri, 26 Jun 2015 20:03:43 +0200 Subject: Add base128 --- ber/obj.go | 18 ++++++++++++++++-- ber/obj_test.go | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) (limited to 'ber') diff --git a/ber/obj.go b/ber/obj.go index e9db78c..735ef97 100644 --- a/ber/obj.go +++ b/ber/obj.go @@ -1,7 +1,21 @@ package ber -func base128(i int) (b []byte) { - return b +func base128(n int) (b []byte) { + l := 0 + + for i := n; i > 0; i >>= 7 { + l++ + } + + for i := l - 1; i >= 0; i-- { + o := byte(n >> uint(i*7)) + o &= 0x7F + if i != 0 { + o |= 0x80 + } + b = append(b, o) + } + return } func debase128(b []byte) int { diff --git a/ber/obj_test.go b/ber/obj_test.go index 995db5c..73cc3f5 100644 --- a/ber/obj_test.go +++ b/ber/obj_test.go @@ -1 +1,19 @@ package ber + +import ( + "testing" + "bytes" +) + +func testBase128(t *testing.T, n int, e []byte) { + a := base128(n) + if !bytes.Equal(a, e) { + t.Error("Base128", n, "expexted", e, "got", a) + } +} + +func TestBase128(t *testing.T) { + testBase128(t, 643, []byte{0x85, 0x03}) + testBase128(t, 113549, []byte{0x86, 0xF7, 0x0D}) + testBase128(t, 49152, []byte{0x83, 0x80, 0x00}) +} -- cgit v1.2.3