Skip to content

Instantly share code, notes, and snippets.

@ehmo
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehmo/ec4ab4b57578682a6ae8 to your computer and use it in GitHub Desktop.
Save ehmo/ec4ab4b57578682a6ae8 to your computer and use it in GitHub Desktop.
Implementation of an URL shortener using base62 encoding in Go
package main
import (
"fmt"
"strings"
)
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// Integer power: compute a**b using binary powering algorithm
// See Donald Knuth, The Art of Computer Programming, Volume 2, Section 4.6.3
func Pow(a, b int) int {
p := 1
for b > 0 {
if b&1 != 0 {
p *= a
}
b >>= 1
a *= a
}
return p
}
func base62Encode(num int) []byte {
code := make([]byte, 0, 128)
for num > 0 {
rem := num % len(alphabet)
num = num / len(alphabet)
code = append(code, alphabet[rem])
}
for i, j := 0, len(code)-1; i < j; i, j = i+1, j-1 {
code[i], code[j] = code[j], code[i]
}
return code
}
func base62Decode(code string) int {
num := 0
i := 0
for _, char := range code {
power := (len(code) - (i + 1))
num = num + strings.Index(alphabet, string(char)) * Pow(len(alphabet), power)
i++
}
return num
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment