优化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 package convx
import ( import (
"errors"
"fmt"
"strings" "strings"
) )
@@ -8,13 +10,17 @@ import (
// 10进制的数字转换为64进制的字符串,用于生成短链接 // 10进制的数字转换为64进制的字符串,用于生成短链接
// 64进制的字符集,可以自定义 // 64进制的字符集,可以自定义
const base64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/" const base64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#*"
// DecToBase64 将10进制的数字转换为64进制的字符串 // DecToBase64 将10进制的数字转换为64进制的字符串
func Encode10To64(n int) string { func Encode10To64(n int64) (string, error) {
if n == 0 { if n < 0 {
return "0" return "", fmt.Errorf("n must be positive")
} }
if n == 0 {
return "0", nil
}
s := "" s := ""
for n > 0 { for n > 0 {
// 取余数,作为64进制的一位 // 取余数,作为64进制的一位
@@ -26,22 +32,21 @@ func Encode10To64(n int) string {
// 除以64,继续下一轮循环 // 除以64,继续下一轮循环
n = n / 64 n = n / 64
} }
return s return s, nil
} }
// Base64ToDec 将64进制的字符串转换为10进制的数字 // Base64ToDec 将64进制的字符串转换为10进制的数字
func Decode64To10(s string) int { func Decode64To10(s string) (int64, error) {
n := 0 n := int64(0)
// 遍历字符串的每个字符 // 遍历字符串的每个字符
for _, c := range s { for _, c := range s {
// 在字符集中找到字符的索引,作为64进制的一位 // 在字符集中找到字符的索引,作为64进制的一位
i := strings.Index(base64, string(c)) i := strings.Index(base64, string(c))
if i == -1 { if i == -1 {
// 如果字符不在字符集中,返回-1表示错误 return 0, errors.New("invalid character: " + string(c))
return -1
} }
// 累加到结果数字中,每次乘以64 // 累加到结果数字中,每次乘以64
n = n*64 + i n = n*64 + int64(i)
} }
return n return n, nil
} }
+31
View File
@@ -0,0 +1,31 @@
package convx_test
import (
"fmt"
"math"
"testing"
"code.yun.ink/pkg/convx"
)
func Test10to64(t *testing.T) {
var tests = []struct {
in int64
}{
{math.MaxInt64},
{-987654321},
// {-1234567890},
// {-987654321},
{0},
}
for _, test := range tests {
s, err := convx.Encode10To64(test.in)
fmt.Println(test.in, s, err)
n, err := convx.Decode64To10(s)
fmt.Println(n, err)
if n != test.in {
t.Errorf("10to64: %d != %d", n, test.in)
}
}
}
+3 -3
View File
@@ -8,8 +8,8 @@ import (
func Test64(t *testing.T) { func Test64(t *testing.T) {
// 测试10进制转64进制 // 测试10进制转64进制
var v_int int = 123456789 var v_int int64 = 123456789
str := convx.Encode10To64(v_int) str,_ := convx.Encode10To64(v_int)
if str != "7MyqL" { if str != "7MyqL" {
t.Fail() t.Fail()
t.Log(str) t.Log(str)
@@ -17,7 +17,7 @@ func Test64(t *testing.T) {
// 测试64进制转10进制 // 测试64进制转10进制
var v_string string = "7MyqL" var v_string string = "7MyqL"
i := convx.Decode64To10(v_string) i,_ := convx.Decode64To10(v_string)
if i != 123456789 { if i != 123456789 {
t.Fail() t.Fail()
t.Log(i) t.Log(i)