优化64进制转换
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
@@ -8,8 +8,8 @@ import (
|
||||
|
||||
func Test64(t *testing.T) {
|
||||
// 测试10进制转64进制
|
||||
var v_int int = 123456789
|
||||
str := convx.Encode10To64(v_int)
|
||||
var v_int int64 = 123456789
|
||||
str,_ := convx.Encode10To64(v_int)
|
||||
if str != "7MyqL" {
|
||||
t.Fail()
|
||||
t.Log(str)
|
||||
@@ -17,7 +17,7 @@ func Test64(t *testing.T) {
|
||||
|
||||
// 测试64进制转10进制
|
||||
var v_string string = "7MyqL"
|
||||
i := convx.Decode64To10(v_string)
|
||||
i,_ := convx.Decode64To10(v_string)
|
||||
if i != 123456789 {
|
||||
t.Fail()
|
||||
t.Log(i)
|
||||
|
||||
Reference in New Issue
Block a user