-
Notifications
You must be signed in to change notification settings - Fork 0
/
base58.go
52 lines (46 loc) · 1.14 KB
/
base58.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
package encoding
import (
"bytes"
"github.com/chinaDL/whTools/utils"
"math/big"
)
// 该部分代码参考于 https://github.com/golang-module/dongle
const base58table = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
// ByBase58 encodes by base58.
// 通过 base58 编码
func (e Encode) ByBase58() Encode {
if len(e.src) == 0 {
return e
}
intBytes := big.NewInt(0).SetBytes(e.src)
int0, int58 := big.NewInt(0), big.NewInt(58)
for intBytes.Cmp(big.NewInt(0)) > 0 {
intBytes.DivMod(intBytes, int58, int0)
e.dst = append(e.dst, utils.Str2bytes(base58table)[int0.Int64()])
}
e.dst = reverseBytes(e.dst)
return e
}
// ByBase58 decodes by base58.
// 通过 base58 解码
func (d Decode) ByBase58() Decode {
if len(d.src) == 0 {
return d
}
Int0 := big.NewInt(0)
for _, v := range d.src {
index := bytes.IndexByte([]byte(base58table), v)
Int0.Mul(Int0, big.NewInt(58))
Int0.Add(Int0, big.NewInt(int64(index)))
}
d.dst = Int0.Bytes()
return d
}
// reverses byte slice.
// 反转字节切片
func reverseBytes(b []byte) []byte {
for i := 0; i < len(b)/2; i++ {
b[i], b[len(b)-1-i] = b[len(b)-1-i], b[i]
}
return b
}