forked from librespot-org/librespot-golang
/
base62.go
58 lines (48 loc) · 1.06 KB
/
base62.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
package utils
import (
"fmt"
"math/big"
"strings"
)
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func Convert62(id string) []byte {
base := big.NewInt(62)
n := &big.Int{}
for _, c := range []byte(id) {
d := big.NewInt(int64(strings.IndexByte(alphabet, c)))
n = n.Mul(n, base)
n = n.Add(n, d)
}
nBytes := n.Bytes()
if len(nBytes) < 16 {
paddingBytes := make([]byte, 16-len(nBytes))
nBytes = append(paddingBytes, nBytes...)
}
return nBytes
}
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func ConvertTo62(raw []byte) string {
bi := big.Int{}
bi.SetBytes(raw)
rem := big.NewInt(0)
base := big.NewInt(62)
zero := big.NewInt(0)
result := ""
for bi.Cmp(zero) > 0 {
_, rem = bi.DivMod(&bi, base, rem)
result += string(alphabet[int(rem.Uint64())])
}
for len(result) < 22 {
result += "0"
}
return reverse(result)
}
func Base62ToHex(b62 string) string {
return fmt.Sprintf("%x", Convert62(b62))
}