parent
12fcbd8d19
commit
dee606e6ab
@ -0,0 +1,41 @@
|
||||
package str
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var Bit62Chars string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
|
||||
// 翻转[]byte
|
||||
func ByteReverse(a []byte) {
|
||||
for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {
|
||||
a[left], a[right] = a[right], a[left]
|
||||
}
|
||||
}
|
||||
|
||||
// int64 -> string
|
||||
func (s *Str) Bit62Encode(num int64) string {
|
||||
bytes := []byte{}
|
||||
for num > 0 {
|
||||
bytes = append(bytes, Bit62Chars[num%62])
|
||||
num = num / 62
|
||||
}
|
||||
ByteReverse(bytes)
|
||||
return string(bytes)
|
||||
}
|
||||
|
||||
// string -> int64
|
||||
func (s *Str) Bit62Decode(str string) int64 {
|
||||
var num int64
|
||||
n := len(str)
|
||||
for i := 0; i < n; i++ {
|
||||
pos := strings.IndexByte(Bit62Chars, str[i])
|
||||
num += int64(math.Pow(62, float64(n-i-1)) * float64(pos))
|
||||
}
|
||||
return num
|
||||
}
|
||||
|
||||
func (s *Str) Bit62Add(base, value string) string {
|
||||
return s.Bit62Encode(s.Bit62Decode(base) + s.Bit62Decode(value))
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
package str
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReverse(tt *testing.T) {
|
||||
a := []byte("hello world")
|
||||
fmt.Println(a)
|
||||
//[104 101 108 108 111 32 119 111 114 108 100]
|
||||
ByteReverse(a)
|
||||
fmt.Println(a)
|
||||
//[100 108 114 111 119 32 111 108 108 101 104]
|
||||
|
||||
}
|
||||
|
||||
func TestBit62Add(t *testing.T) {
|
||||
var num int64 = 1234567890
|
||||
var num1 int64 = 5
|
||||
numB62 := StrTool.Bit62Encode(num)
|
||||
num1B62 := StrTool.Bit62Encode(num1)
|
||||
fmt.Println(numB62)
|
||||
fmt.Println(num1B62)
|
||||
num2B62 := StrTool.Bit62Add(numB62, num1B62)
|
||||
num2 := StrTool.Bit62Decode(num2B62)
|
||||
fmt.Println(num2B62)
|
||||
fmt.Println(num2)
|
||||
fmt.Println(StrTool.Bit62Add("ly7vp", "1"))
|
||||
|
||||
}
|
||||
@ -0,0 +1,4 @@
|
||||
package str
|
||||
|
||||
type Str struct {
|
||||
}
|
||||
@ -0,0 +1,3 @@
|
||||
package str
|
||||
|
||||
var StrTool Str
|
||||
Loading…
Reference in new issue