Created
January 12, 2022 02:39
-
-
Save evzpav/7002fc94c437bb73bc8815114253497d to your computer and use it in GitHub Desktop.
Golang base62 encoding/decoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"strings" | |
) | |
const chars string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" | |
func main() { | |
n := uint64(10000) | |
fmt.Println(Encode(n)) | |
fmt.Println(Decode("2bI")) | |
} | |
func Encode(nb uint64) string { | |
base := chars | |
var buf bytes.Buffer | |
l := uint64(len(base)) | |
if nb/l != 0 { | |
encode(nb/l, &buf, base) | |
} | |
buf.WriteByte(base[nb%l]) | |
return buf.String() | |
} | |
func encode(nb uint64, buf *bytes.Buffer, base string) { | |
l := uint64(len(base)) | |
if nb/l != 0 { | |
encode(nb/l, buf, base) | |
} | |
buf.WriteByte(base[nb%l]) | |
} | |
func Decode(enc string) uint64 { | |
base := chars | |
var nb uint64 | |
lbase := len(base) | |
le := len(enc) | |
for i := 0; i < le; i++ { | |
mult := 1 | |
for j := 0; j < le-i-1; j++ { | |
mult *= lbase | |
} | |
nb += uint64(strings.IndexByte(base, enc[i]) * mult) | |
} | |
return nb | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment