Last active
August 29, 2015 14:22
-
-
Save ehmo/ec4ab4b57578682a6ae8 to your computer and use it in GitHub Desktop.
Implementation of an URL shortener using base62 encoding 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 ( | |
"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