4 Commits

Author SHA1 Message Date
yun 832e70ba48 添加部分测试 2024-01-11 21:48:44 +08:00
yun 97f9a0cb86 提交 2024-01-11 21:40:17 +08:00
yun c0cd260a86 添加进制转换 2024-01-11 21:36:23 +08:00
yun 659840adca 提交 2023-12-03 21:22:05 +08:00
3 changed files with 67 additions and 2 deletions
+47
View File
@@ -0,0 +1,47 @@
package convx
import (
"strings"
)
// 说明
// 10进制的数字转换为64进制的字符串,用于生成短链接
// 64进制的字符集,可以自定义
const base64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"
// DecToBase64 将10进制的数字转换为64进制的字符串
func Encode10To64(n int) string {
if n == 0 {
return "0"
}
s := ""
for n > 0 {
// 取余数,作为64进制的一位
r := n % 64
// 从字符集中找到对应的字符
c := string(base64[r])
// 拼接到结果字符串的前面
s = c + s
// 除以64,继续下一轮循环
n = n / 64
}
return s
}
// Base64ToDec 将64进制的字符串转换为10进制的数字
func Decode64To10(s string) int {
n := 0
// 遍历字符串的每个字符
for _, c := range s {
// 在字符集中找到字符的索引,作为64进制的一位
i := strings.Index(base64, string(c))
if i == -1 {
// 如果字符不在字符集中,返回-1表示错误
return -1
}
// 累加到结果数字中,每次乘以64
n = n*64 + i
}
return n
}
+19 -1
View File
@@ -3,9 +3,27 @@ package convx_test
import (
"testing"
"code.yun.ink/open/utils/convx"
"code.yun.ink/pkg/convx"
)
func Test64(t *testing.T) {
// 测试10进制转64进制
var v_int int = 123456789
str := convx.Encode10To64(v_int)
if str != "7MyqL" {
t.Fail()
t.Log(str)
}
// 测试64进制转10进制
var v_string string = "7MyqL"
i := convx.Decode64To10(v_string)
if i != 123456789 {
t.Fail()
t.Log(i)
}
}
func TestConvToString(t *testing.T) {
// 日志
// t.Log("hello world")
+1 -1
View File
@@ -1,3 +1,3 @@
module code.yun.ink/pkg/convx
go 1.19
go 1.20