You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.1 KiB

4 years ago
package baseCode
import (
"strings"
)
4 years ago
const (
BASE = "E8S2DZX9WYLTN6BQF7CP5IK3MJUAR4HV"
DECIMAL = 32
PAD = "A"
LEN = 8
)
4 years ago
4 years ago
// id转code
4 years ago
4 years ago
func Encode(uid uint64) string {
id := uid
mod := uint64(0)
res := ""
for id != 0 {
mod = id % DECIMAL
id = id / DECIMAL
res += string(BASE[mod])
4 years ago
}
4 years ago
resLen := len(res)
if resLen < LEN {
res += PAD
for i := 0; i < LEN-resLen-1; i++ {
res += string(BASE[(int(uid)+i)%DECIMAL])
4 years ago
}
}
4 years ago
return res
4 years ago
}
4 years ago
func Decode(code string) uint64 {
res := uint64(0)
lenCode := len(code)
baseArr := []byte(BASE) // 字符串进制转换为byte数组
baseRev := make(map[byte]int) // 进制数据键值转换为map
for k, v := range baseArr {
baseRev[v] = k
4 years ago
}
4 years ago
// 查找补位字符的位置
isPad := strings.Index(code, PAD)
if isPad != -1 {
lenCode = isPad
4 years ago
}
4 years ago
r := 0
for i := 0; i < lenCode; i++ {
// 补充字符直接跳过
if string(code[i]) == PAD {
continue
}
index, ok := baseRev[code[i]]
4 years ago
if !ok {
4 years ago
return 0
4 years ago
}
4 years ago
b := uint64(1)
4 years ago
for j := 0; j < r; j++ {
4 years ago
b *= DECIMAL
4 years ago
}
4 years ago
res += uint64(index) * b
4 years ago
r++
}
4 years ago
return res
4 years ago
}