Created
June 9, 2015 22:09
-
-
Save kylelemons/0757023b67cc5e4de345 to your computer and use it in GitHub Desktop.
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 b62 | |
import ( | |
"math" | |
"testing" | |
) | |
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
func base62EncodeB(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 base62EncodeS(num int) string { | |
code := "" | |
for num > 0 { | |
rem := num % len(alphabet) | |
num = num / len(alphabet) | |
code = string(alphabet[rem]) + code | |
} | |
return code | |
} | |
func BenchmarkEncodeS(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
base62EncodeS(math.MaxInt64 - i) | |
} | |
} | |
func BenchmarkEncodeB(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
base62EncodeB(math.MaxInt64 - i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment