How to convert a number to any base in Go

1 Answer

0 votes
package main

import (
    "errors"
    "fmt"
)

func ToBase(n int, base int) (string, error) {
    const digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    if base < 2 || base > 36 {
        return "", errors.New("base must be between 2 and 36")
    }

    if n == 0 {
        return "0", nil
    }

    result := make([]byte, 0)

    for n > 0 {
        remainder := n % base
        result = append(result, digits[remainder])
        n /= base
    }

    // Reverse the slice
    for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
        result[i], result[j] = result[j], result[i]
    }

    return string(result), nil
}

func main() {
    number := 255

    bases := []int{2, 8, 16, 36}

    for _, b := range bases {
        converted, err := ToBase(number, b)
        if err != nil {
            fmt.Println("Error:", err)
            continue
        }
        fmt.Printf("%d in base %d = %s\n", number, b, converted)
    }
}



/*
run:

255 in base 2 = 11111111
255 in base 8 = 377
255 in base 16 = FF
255 in base 36 = 73

*/

 



answered Feb 21 by avibootz
...