English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use functions in Kotlin to convert binary numbers to octal numbers and vice versa.
In this program, we will first convert the binary number to decimal. Then, the decimal number is converted to octal.
fun main(args: Array<String>) { val binary: Long = 101001 val octal = convertBinarytoOctal(binary) println("$binary 二进制 = $octal in octal") } fun convertBinarytoOctal(binaryNumber: Long): Int { var binaryNumber = binaryNumber var octalNumber = 0 var decimalNumber = 0 var i = 0 while (binaryNumber.toInt() != 0) { decimalNumber += (binaryNumber % 10 * Math.pow(2.0, i.toDouble())).toInt() ++i binaryNumber /= 10 } i = 1 while (decimalNumber != 0) { octalNumber += (decimalNumber % 8 * i decimalNumber /= 8 i *= 10 } return octalNumber }
When running this program, the output is:
101001 Binary = 51 Decimal
This conversion occurs as follows:
Binary to decimal 1 * 25 + 0 * 24 + 1 * 23 + 0 * 22 + 0 * 21 + 1 * 20 = 41 Decimal to octal 8 | 418 | 5 -- 1 8 | 0 -- 5 (51)
In this program, the octal number is first converted to decimal. Then, the decimal number is converted to binary.
fun main(args: Array<String>) { val octal = 67 val binary = convertOctalToBinary(octal) println("$octal 十进制 = $binary in binary") } fun convertOctalToBinary(octalNumber: Int): Long { var octalNumber = octalNumber var decimalNumber = 0 var i = 0 var binaryNumber: Long = 0 while (octalNumber != 0) { decimalNumber += (octalNumber % 10 * Math.pow(8.0, i.toDouble())).toInt() ++i octalNumber /= 10 } i = 1 while (decimalNumber != 0) { binaryNumber += (decimalNumber % 2 * .toLong() decimalNumber /= 2 i *= 10 } return binaryNumber }
When running this program, the output is:
67 Decimal = 110111 Binary
This conversion occurs as follows:
Octal to Decimal 6 * 81 + 7 * 80 = 55 Decimal to Binary 2 | 552 | 27 -- 1 2 | 13 -- 1 2 | 6 -- 1 2 | 3 -- 0 2 | 1 -- 1 2 | 0 -- 1 (110111)
This is the equivalent Java code:Java Program to Convert Binary to Octal and Vice Versa