how can one convert from base 10 to any base 2-36 in go?
in javascript you just
Number.toString(radix?)
e.g.
var number = 12345; console.log(my_number.toString(36).toUpperCase());
in go this is how you can achieve the same effect
func convertToAnyBase2to36(num int64, base int64) string {
var len int64 = base
var source_string = []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "J", "I", "J", "K",
"L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X","Y","Z"}
code := "";
for {
if num <= 0 {
break
}
mod := num % len;
num = (num - mod) / len;
code = source_string[mod]+code;
}
return code
}
e.g
fmt.Println(convertToAnyBase2to36(12354,2))
In Go you have strconv.FormatInt()
(and strconv.FormatUint()
):
fmt.Println(strconv.FormatInt(12345, 2))
fmt.Println(strconv.FormatInt(12345, 16))
fmt.Println(strconv.FormatInt(12345, 32))
This will output (try it on the Go Playground):
11000000111001
3039
c1p