go-nurl/base58/base58.go

54 lines
749 B
Go
Raw Permalink Normal View History

2024-09-16 16:06:11 +00:00
package base58
import (
"math"
"slices"
)
var (
byteabet = []byte("bMJZSrnxEyq8kN3UYQL5oXwV7BCFRtvpmDf1shAuHzKicTjeG29Pg4adW6")
base = len(byteabet)
)
func Encode(num int) string {
encoded := ""
worknum := num
for worknum > 0 {
remainder := worknum % base
worknum = worknum / base
encoded = string(byteabet[remainder]) + encoded
}
return encoded
}
func Decode(encoded string) int {
decoded := 0
workEncoded := encoded
for len(workEncoded) > 0 {
index := workEncoded[0:1]
power := len(workEncoded) - 1
idx := slices.IndexFunc(byteabet, func(c byte) bool {
return c == index[0]
})
decoded += idx * int(math.Pow(float64(base), float64(power)))
workEncoded = workEncoded[1:]
}
return decoded
}