89 lines
1.9 KiB
Go
89 lines
1.9 KiB
Go
package pkg
|
|
|
|
import (
|
|
"fmt"
|
|
"math/big"
|
|
"strings"
|
|
)
|
|
|
|
var BASE = []string{
|
|
"A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
|
|
"a", "b", "c", "d", "e", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
|
|
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
|
|
}
|
|
|
|
type Converter struct {
|
|
base []string
|
|
baseCount *big.Int
|
|
}
|
|
|
|
func NewConverter() *Converter {
|
|
c := &Converter{
|
|
base: BASE,
|
|
baseCount: big.NewInt(int64(len(BASE))),
|
|
}
|
|
return c
|
|
}
|
|
|
|
func (c *Converter) DeBase(id string) *big.Int {
|
|
dedicate := make(map[string]int)
|
|
for i, v := range c.base {
|
|
dedicate[v] = i
|
|
}
|
|
|
|
id = strings.TrimLeft(id, c.base[0])
|
|
id = reverseString(id)
|
|
|
|
v := big.NewInt(0)
|
|
bigBaseCount := new(big.Int).Set(c.baseCount)
|
|
bigIndex := new(big.Int)
|
|
|
|
for i, char := range id {
|
|
index := dedicate[string(char)]
|
|
bigIndex.SetInt64(int64(index))
|
|
pow := new(big.Int).Exp(bigBaseCount, big.NewInt(int64(i)), nil)
|
|
mul := new(big.Int).Mul(bigIndex, pow)
|
|
v = new(big.Int).Add(v, mul)
|
|
}
|
|
|
|
return v
|
|
}
|
|
|
|
func (c *Converter) EnBase(num *big.Int, pad int, format int) string {
|
|
arr := make([]string, 0)
|
|
zero := big.NewInt(0)
|
|
bigBaseCount := new(big.Int).Set(c.baseCount)
|
|
|
|
for num.Cmp(zero) != 0 {
|
|
mod := new(big.Int).Mod(num, bigBaseCount)
|
|
arr = append(arr, c.base[mod.Int64()])
|
|
num = new(big.Int).Div(num, bigBaseCount)
|
|
}
|
|
|
|
for len(arr) < pad {
|
|
arr = append(arr, c.base[0])
|
|
}
|
|
|
|
reverseStringSlice(arr)
|
|
|
|
if format == 1 {
|
|
return strings.Join(arr, "")
|
|
} else {
|
|
return fmt.Sprintf("%v", arr)
|
|
}
|
|
}
|
|
|
|
func reverseString(s string) string {
|
|
runes := []rune(s)
|
|
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
|
|
runes[i], runes[j] = runes[j], runes[i]
|
|
}
|
|
return string(runes)
|
|
}
|
|
|
|
func reverseStringSlice(s []string) {
|
|
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
|
|
s[i], s[j] = s[j], s[i]
|
|
}
|
|
}
|