-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode.go
61 lines (57 loc) · 1.08 KB
/
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package constbn
/*
* Encode an integer into its big-endian unsigned representation. The
* output length in bytes is provided (parameter 'len'); if the length
* is too short then the integer is appropriately truncated; if it is
* too long then the extra bytes are set to 0.
*/
func simpleEncode(x []Base) []byte {
result := make([]byte, len(x)*5)
Encode(result, x)
return result
}
// Encode will encode the given number as a big endian unsigned byte array
func Encode(dst []byte, x []Base) {
xlen := baseLen(x)
if xlen == 0 {
zeroizeBytes(dst)
return
}
l := len(dst)
buf := l
k := one
acc := zero
accLen := uint(0)
for l != 0 {
w := zero
if k <= xlen {
w = x[k]
}
k++
if accLen == 0 {
acc = w
accLen = 31
} else {
z := acc | (w << accLen)
accLen--
acc = w >> (31 - accLen)
if l >= 4 {
buf -= 4
l -= 4
enc32be(dst[buf:], z)
} else {
switch l {
case 3:
dst[buf-3] = byte(z >> 16)
fallthrough
case 2:
dst[buf-2] = byte(z >> 8)
fallthrough
case 1:
dst[buf-1] = byte(z)
}
return
}
}
}
}