Kotlin Program to Convert Octal Number to Decimal and vice-versa

Example 1: Program to Convert Decimal to Octal

fun main(args: Array<String>) {
    val decimal = 78
    val octal = convertDecimalToOctal(decimal)
    println("$decimal in decimal = $octal in octal")
}

fun convertDecimalToOctal(decimal: Int): Int {
    var decimal = decimal
    var octalNumber = 0
    var i = 1

    while (decimal != 0) {
        octalNumber += decimal % 8 * i
        decimal /= 8
        i *= 10
    }

    return octalNumber
}

When you run the program, the output will be:

78 in decimal = 116 in octal

This conversion takes place as:

8 | 78
8 | 9 -- 6
8 | 1 -- 1
8 | 0 -- 1
(116)

Example 2: Program to Convert Octal to Decimal

fun main(args: Array<String>) {
    val octal = 116
    val decimal = convertOctalToDecimal(octal)
    println("$octal in octal = $decimal in decimal")
}

fun convertOctalToDecimal(octal: Int): Int {
    var octal = octal
    var decimalNumber = 0
    var i = 0

    while (octal != 0) {
        decimalNumber += (octal % 10 * Math.pow(8.0, i.toDouble())).toInt()
        ++i
        octal /= 10
    }

    return decimalNumber
}

When you run the program, the output will be:

116 in octal = 78 in decimal

This conversion takes place as:

1 * 82 + 1 * 81 + 6 * 80 = 78

Here's the equivalent Java code: Java program to convert octal to decimal and vice-versa

Did you find this article helpful?