Skip to content

Instantly share code, notes, and snippets.

@evzpav
Created January 12, 2022 02:39
Show Gist options
  • Save evzpav/7002fc94c437bb73bc8815114253497d to your computer and use it in GitHub Desktop.
Save evzpav/7002fc94c437bb73bc8815114253497d to your computer and use it in GitHub Desktop.
Golang base62 encoding/decoding
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