How to convert a number to any base in Kotlin

1 Answer

0 votes
object BaseConvert {

    fun toBase(n: Int, base: Int): String {
        require(base in 2..36) { "Base must be between 2 and 36" }

        if (n == 0) return "0"

        val digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        var value = n
        val result = StringBuilder()

        while (value > 0) {
            val remainder = value % base
            result.append(digits[remainder])
            value /= base
        }

        return result.reverse().toString()
    }

    @JvmStatic
    fun main(args: Array<String>) {
        val number = 25
        val bases = listOf(2, 8, 16, 36)

        for (b in bases) {
            println("$number in base $b = ${toBase(number, b)}")
        }
    }
}


/*
 The decimal number 25 is represented as P in base-36. 
 Base-36 uses digits 0-9 followed by letters A-Z (where A=10, B=11, ..., P=25, ..., Z=35) 
 to represent values. 
*/



/*
run:

25 in base 2 = 11001
25 in base 8 = 31
25 in base 16 = 19
25 in base 36 = P

*/

 



answered Feb 21 by avibootz
...