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

Kotlin is a modern and popular programming language that is widely used for developing various software applications, including mobile apps, web apps, and desktop applications.

In this tutorial, we’ll focus on converting octal numbers to decimal and vice versa using Kotlin.


Octal to Decimal Conversion in Kotlin

Octal is a base-8 number system that uses digits from 0 to 7.

Decimal, on the other hand, is a base-10 number system that uses digits from 0 to 9.

To convert an octal number to decimal in Kotlin, we can use the following steps:

  1. Initialize a variable to store the decimal value.
  2. Iterate over each digit of the octal number starting from the least significant digit.
  3. Multiply each digit with 8 to the power of its position.
  4. Add the resulting value to the decimal variable.
  5. Once all digits have been processed, the decimal value is the final result.

Here is the Kotlin code to perform octal to decimal conversion:

fun octalToDecimal(octal: Int): Int {
var decimal = 0
var i = 0
var n = octal
while (n != 0) {
val digit = n % 10
decimal += digit * Math.pow(8.0, i.toDouble()).toInt()
i++
n /= 10
}
return decimal
}

To use this function, we can call it like this:

val octalNumber = 1234
val decimalNumber = octalToDecimal(octalNumber)
println("Octal $octalNumber converted to Decimal is $decimalNumber")

This will output: “Octal 1234 converted to Decimal is 668”.

Decimal to Octal Conversion in Kotlin

To convert a decimal number to octal in Kotlin, we can use the following steps:

  1. Initialize a variable to store the octal value.
  2. Divide the decimal number by 8 and store the remainder.
  3. Multiply the remainder by 10 to the power of its position.
  4. Add the resulting value to the octal variable.
  5. Divide the decimal number by 8 and repeat steps 2-4 until the decimal number becomes 0.
  6. Once all remainders have been processed, the octal value is the final result.

Here is the Kotlin code to perform decimal to octal conversion:

fun decimalToOctal(decimal: Int): Int {
var octal = 0
var i = 1
var n = decimal
while (n != 0) {
octal += (n % 8) * i
n /= 8
i *= 10
}
return octal
}

To use this function, we can call it like this:

val decimalNumber = 1234
val octalNumber = decimalToOctal(decimalNumber)
println("Decimal $decimalNumber converted to Octal is $octalNumber")

This will output: “Decimal 1234 converted to Octal is 2322”.

In conclusion, Kotlin provides an easy and efficient way to perform octal to decimal and decimal to octal conversions.

By using the steps and code snippets provided in this Kotlin tutorial, you should be able to easily perform these conversions in your Kotlin projects.