-
Notifications
You must be signed in to change notification settings - Fork 0
/
base58.go
49 lines (40 loc) · 985 Bytes
/
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
package base58
import (
"bytes"
"math/big"
)
var base58 = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
func Encode(str string) string {
sb := []byte(str)
sbt := big.NewInt(0).SetBytes(sb)
var modSlice []byte
for sbt.Cmp(big.NewInt(0)) > 0 {
mod := big.NewInt(0)
sbt.DivMod(sbt, big.NewInt(58), mod)
modSlice = append(modSlice, base58[mod.Int64()])
}
for _, elem := range sb {
if elem != 0 {
break
} else if elem == 0 {
modSlice = append(modSlice, byte('1'))
}
}
return string(reverseBytes(modSlice))
}
func reverseBytes(bytes []byte) []byte {
for i := 0; i < len(bytes)/2; i++ {
bytes[i], bytes[len(bytes)-1-i] = bytes[len(bytes)-1-i], bytes[i]
}
return bytes
}
func Decode(str string) []byte {
strByte := []byte(str)
ret := big.NewInt(0)
for _, byteElem := range strByte {
index := bytes.IndexByte(base58, byteElem)
ret.Mul(ret, big.NewInt(58))
ret.Add(ret, big.NewInt(int64(index)))
}
return ret.Bytes()
}