diff --git a/base2.go b/base2.go index fef6cef..e4e5ed2 100644 --- a/base2.go +++ b/base2.go @@ -4,6 +4,7 @@ import ( "fmt" "math" "strconv" + "strings" ) // binaryEncodeToString takes an array of bytes and returns @@ -19,9 +20,9 @@ func binaryEncodeToString(src []byte) string { func encodeBinary(dst []byte, src []byte) { for i := 0; i < len(src); i++ { t := src[i] - for j := i * 8; j < (i*8)+8; j++ { - higherPower := math.Pow(2, float64(7-(j%8))) - if float64(t) >= higherPower { + for j := i << 3; j < (i<<3)+8; j++ { + higherPower := math.Pow(2, float64(7-(j&7))) + if t >= byte(higherPower) { dst[j] = '1' t = t - byte(higherPower) } else { @@ -34,12 +35,12 @@ func encodeBinary(dst []byte, src []byte) { // decodeBinaryString takes multibase binary representation // and returns a byte array func decodeBinaryString(s string) ([]byte, error) { - if len(s)%8 != 0 { - return nil, fmt.Errorf("cannot decode multibase: %s", - "length should be a multiple of 4") + if len(s)&7 != 0 { + // prepend the padding + s = strings.Repeat("0", 8-len(s)&7) + s } - data := make([]byte, len(s)/8) + data := make([]byte, len(s)>>3) for i, dstIndex := 0, 0; i < len(s); i = i + 8 { value, err := strconv.ParseInt(s[i:i+8], 2, 0)