Defining the Base62 algorithm

We saw how the Base62 algorithm works in the previous chapters. Here is the solid implementation of that algorithm. The logic is purely mathematical and can be found everywhere on the web. Take a look at the following code:

package base62 import ( "math" "strings" ) const base = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const b = 62 // Function encodes the given database ID to a base62 string func ToBase62(num int) string{ r := num % b res := string(base[r]) div := num / b q := int(math.Floor(float64(div))) for q != 0 { r = q % b temp := q / b q = int(math.Floor(float64(temp))) res = string(base[int(r)]) + res } return string(res) } // Function decodes a given base62 string to datbase ID ...

Get Building RESTful Web services with Go now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.