Skip to content

Instantly share code, notes, and snippets.

@tomekc
Last active March 16, 2021 23:32
Show Gist options
  • Save tomekc/f93fe7e6d2b798e237aff80501a6ece7 to your computer and use it in GitHub Desktop.
Save tomekc/f93fe7e6d2b798e237aff80501a6ece7 to your computer and use it in GitHub Desktop.
Build human-readable ID using Base32 in Go
package main
import (
"encoding/base32"
"fmt"
)
func main() {
id := 202790
// Assume the ID is 32-bit integer, fill the slice of size 4 bytes with bits
data := []byte{ byte((id >> 24) & 0xff), byte((id >> 16) & 0xff), byte((id >> 8) & 0xff), byte(id & 0xff)}
padding := base32.NoPadding
str := base32.StdEncoding.WithPadding(padding).EncodeToString(data)
fmt.Println(str) // AABRQJQ
decodedBytes, _ := base32.StdEncoding.WithPadding(padding).DecodeString(str)
fmt.Println(decodedBytes) // [0 3 24 38]
decodedID := int(decodedBytes[0]) << 24 + int(decodedBytes[1]) << 16 + int(decodedBytes[2]) << 8 + int(decodedBytes[3])
fmt.Println(decodedID)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment