English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn to use functions in Kotlin to convert octal numbers to decimal numbers and vice versa.
fun main(args: Array<String>) { val decimal = 78 val octal = convertDecimalToOctal(decimal) println("$decimal 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 the program is run, the output is:
78 decimal = 116 octal
This conversion occurs as follows:
8 | 788 | 9 -- 6 8 | 1 -- 1 8 | 0 -- 1 (116)
fun main(args: Array<String>) { val octal = 116 val decimal = convertOctalToDecimal(octal) println("$octal 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 the program is run, the output is:
116 Octal = 78 Decimal
This conversion occurs as follows:
1 * 82 + 1 * 81 + 6 * 80 = 78
This is the equivalent Java code:Java Program to Convert Octal to Decimal and vice versa