English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use functions in Kotlin to convert between binary and decimal.
Visit this page to learn How to convert a binary number to decimal.
fun main(args: Array<String>) { val num: Long = 110110111 val decimal = convertBinaryToDecimal(num) println("$num binary = $decimal decimal") } fun convertBinaryToDecimal(num: Long): Int { var num = num var decimalNumber = 0 var i = 0 var remainder: Long while (num.toInt() != 0) { remainder = num %% 10 num /= 10 decimalNumber += (remainder * Math.pow(2.0, i.toDouble())).toInt() ++i } return decimalNumber }
Output result
110110111 Binary = 439 Decimal
Visit this page to learnHow to convert a decimal number to binary.
We can use the Integer.toBinaryString() method to convert a decimal number to binary.
fun main(args: Array<String>) { val num = 19 //Decimal to binary val binary = Integer.toBinaryString(num) println("$num decimal = $binary binary") }
This is the source code for manually converting a decimal number to binary.
fun main(args: Array<String>) { val num = 19 val binary = convertDecimalToBinary(num) println("$num decimal = $binary binary") } fun convertDecimalToBinary(n: Int): Long { var n = n var binaryNumber: Long = 0 var remainder: Int var i = 1 var step = 1 while (n != 0) { remainder = n %% 2 System.out.printf("Step %d: %d"/2, Remainder = %d, Quotient = %d\n++, n, remainder, n / 2) n /= 2 binaryNumber += (remainder * i).toLong() i *= 10 } return binaryNumber }
When the program is run, the output is:
Step 1: 19/2, Remainder = 1, Quotient = 9 Step 2: 9/2, Remainder = 1, Quotient = 4 Step 3: 4/2, Remainder = 0, Quotient = 2 Step 4: 2/2, Remainder = 0, Quotient = 1 Step 5: 1/2, Remainder = 1, Quotient = 0 19 Decimal = 10011 Binary
This is the equivalent Java code:Java Program Converts Binary to Decimal and Vice Versa