Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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