Skip to content

Commit

Permalink
Merge pull request #1 from growsumo/fix/unsigned-ints
Browse files Browse the repository at this point in the history
using unsigned ints
  • Loading branch information
davidRichards39 authored Mar 3, 2017
2 parents 7233e4f + 30712fd commit 253dc6f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
14 changes: 7 additions & 7 deletions base62.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@ import (

// BASE62 should always be 0-9,a-z,A-Z
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const base = len(alphabet)
const base = uint(len(alphabet))

var balphabet = []byte(alphabet)

// Encode a positive integer to a Base62 token
func Encode(num int) []byte {
func Encode(num uint) []byte {
if num == 0 {
return []byte{alphabet[0]}
}
// result byte arr
var res []byte
// remainder of modulo
var rem int
var rem uint

// until num is == 0
for num != 0 {
Expand All @@ -39,19 +39,19 @@ func Encode(num int) []byte {
}

// Decode a Base62 token to its original positive integer
func Decode(token []byte) int {
func Decode(token []byte) uint {
// calculate base (should be 62)
tokenlen := len(token)
num := 0
num := uint(0)
idx := 0
// until num is == 0
for _, c := range token {
// calculate remainder
power := (tokenlen - (idx + 1))
// calculate quotient
index := bytes.IndexByte(balphabet, c)
index := uint(bytes.IndexByte(balphabet, c))
// sum num and decode algo
num += index * int(math.Pow(float64(base), float64(power)))
num += index * uint(math.Pow(float64(base), float64(power)))
// increment index token
idx++
}
Expand Down
13 changes: 7 additions & 6 deletions base62_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import (
"testing"
)

var cases = map[int][]byte{
0: []byte("0"),
1: []byte("1"),
100: []byte("1C"),
999: []byte("g7"),
9999999999: []byte("aUKYOz"),
var cases = map[uint][]byte{
0: []byte("0"),
1: []byte("1"),
100: []byte("1C"),
999: []byte("g7"),
9999999999: []byte("aUKYOz"),
13518126808285626735: []byte("g6Babbcj0sv"),
}

func TestEncode(t *testing.T) {
Expand Down

0 comments on commit 253dc6f

Please sign in to comment.