优化64进制转换

This commit is contained in:
Yun
2024-10-28 21:28:58 +08:00
parent 7a1b81ebf2
commit ab8524e5ef
3 changed files with 50 additions and 14 deletions
+16 -11
View File
@@ -1,6 +1,8 @@
package convx
import (
"errors"
"fmt"
"strings"
)
@@ -8,13 +10,17 @@ import (
// 10进制的数字转换为64进制的字符串,用于生成短链接
// 64进制的字符集,可以自定义
const base64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"
const base64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#*"
// DecToBase64 将10进制的数字转换为64进制的字符串
func Encode10To64(n int) string {
if n == 0 {
return "0"
func Encode10To64(n int64) (string, error) {
if n < 0 {
return "", fmt.Errorf("n must be positive")
}
if n == 0 {
return "0", nil
}
s := ""
for n > 0 {
// 取余数,作为64进制的一位
@@ -26,22 +32,21 @@ func Encode10To64(n int) string {
// 除以64,继续下一轮循环
n = n / 64
}
return s
return s, nil
}
// Base64ToDec 将64进制的字符串转换为10进制的数字
func Decode64To10(s string) int {
n := 0
func Decode64To10(s string) (int64, error) {
n := int64(0)
// 遍历字符串的每个字符
for _, c := range s {
// 在字符集中找到字符的索引,作为64进制的一位
i := strings.Index(base64, string(c))
if i == -1 {
// 如果字符不在字符集中,返回-1表示错误
return -1
return 0, errors.New("invalid character: " + string(c))
}
// 累加到结果数字中,每次乘以64
n = n*64 + i
n = n*64 + int64(i)
}
return n
return n, nil
}