-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencode.go
42 lines (35 loc) · 884 Bytes
/
encode.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package base64encoding
import "github.com/4kills/base64encoding/datatypes"
func (enc Encoder64) encode(b []byte) string {
return string(bitsToBase64(datatypes.FromBytes(b), enc.valMap))
}
func bitsToBase64(bits datatypes.BitArray, valMap []byte) []byte {
log64 := 6
runs := bits.Len() / log64
remainder := bits.Len() % log64
overflow := 0
if remainder != 0 {
overflow = 1
}
str := make([]byte, runs+overflow)
if remainder != 0 {
str[0] = valMap[nextNBits(bits, 0, remainder)]
}
for i := 0; i < runs; i++ {
pos := nextNBits(bits, remainder+log64*i, log64)
str[overflow+i] = valMap[pos] //gets the ASCII of the position in the code
}
return str
}
// assert 0 <= n <= 8
func nextNBits(a datatypes.BitArray, idx, n int) byte {
var b byte
for i := 0; i < n; i++ {
bit := a.Get(idx + i)
if !bit {
continue
}
b |= 0x80 >> i
}
return b >> (8 - n)
}