Last active
March 16, 2021 23:32
-
-
Save tomekc/f93fe7e6d2b798e237aff80501a6ece7 to your computer and use it in GitHub Desktop.
Build human-readable ID using Base32 in Go
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 ( | |
"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