github.com/tursom/GoCollections@v0.3.10/util/b62/base62.go (about) 1 package b62 2 3 import ( 4 "bytes" 5 6 "github.com/tursom/GoCollections/util" 7 ) 8 9 var ( 10 digits = []byte("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") 11 ) 12 13 func Encode(n uint64) string { 14 buffer := bytes.NewBuffer(nil) 15 16 for n != 0 { 17 remainder := n % 62 18 buffer.WriteByte(digits[remainder]) 19 n /= 62 20 } 21 22 return string(util.Reverse(buffer.Bytes())) 23 } 24 25 func Decode(str string) uint64 { 26 var sum uint64 27 var base uint64 = 1 28 29 for i := range str { 30 indexByte := bytes.IndexByte(digits, str[len(str)-i-1]) 31 if indexByte < 0 || indexByte >= 62 { 32 panic(indexByte) 33 } 34 sum += uint64(indexByte) * base 35 base *= 62 36 } 37 38 return sum 39 }