Skip to content

Instantly share code, notes, and snippets.

@elias19r
Created August 23, 2020 03:00
Show Gist options
  • Save elias19r/ca968e746fd844a1a991d7b6dd35f353 to your computer and use it in GitHub Desktop.
Save elias19r/ca968e746fd844a1a991d7b6dd35f353 to your computer and use it in GitHub Desktop.
FormatUintBase64
package main
import "log"
func main() {
tests := []struct {
desc string
given uint64
expected string
}{
{"0", 0, "0"},
{"1", 1, "1"},
{"63", 63, "_"},
{"64", 64, "10"},
{"128", 128, "20"},
{"400", 400, "6g"},
{"12345678", 12345678, "L65e"},
{"2^64 - 1", 1<<64 - 1, "f__________"},
}
for i, test := range tests {
result := FormatUintBase64(test.given)
if result != test.expected {
log.Fatalf(
"Test %d failed: desc=%s, given=%d, expected=%s, result=%s\n",
i, test.desc, test.given, test.expected, result,
)
}
}
}
// base64Digits defines an arbitrary list of symbols used to represent a number
// written in base 64.
var base64Digits = []string{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z", "A", "B", "C", "D",
"E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
"Y", "Z", "-", "_",
}
// FormatUintBase64 returns the string representation of n in base 64.
// The result uses digit values defined by base64Digits.
// (Not to be confused with Base64 encoding)
func FormatUintBase64(n uint64) string {
if n == 0 {
return "0"
}
str := ""
for {
if n == 0 {
break
}
str = base64Digits[n&0b111111] + str
n = n >> 6
}
return str
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment