Kotlin Program to Convert Decimal Number to Binary

Given a Decimal Number as Input. Now, write a Kotlin Program to Convert Decimal Number to equivalent binary number.

Input:
4

Output:
100
Input:
6

Output:
110
Input:
5

Output:
101

1. Program to Convert Decimal to Binary

Sourcecode –

import java.util.*
import kotlin.math.pow

fun main() {
    val read = Scanner(System.`in`)

    println("Enter n:")
    var decimalN = read.nextInt()

    var binaryN = 0
    var count = 0
    while (decimalN != 0) {
        val rem = decimalN % 2
        val c = 10.toDouble().pow(count)
        binaryN += (rem * c).toInt()

        decimalN /= 2
        count++
    }
    println("Equivalent Binary: $binaryN")
}

When you run the program, output will be –

Enter n:
120
Equivalent Binary: 1111000
Explanation:

Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.

read.nextInt() means read anything entered by user before space or line break from standard input – Keyboard.

We stored value entered by user in variable decimalN.

Example,
Assume decimalN = 10

  • At decimalN = 10

    Inside while loop,

    rem = 0
    c = 1
    binaryN = 0

    Now, decimalN = 5
    count = 1

  • At decimalN = 5

    Inside while loop,

    rem = 1
    c = 10
    binaryN = 10

    Now, decimalN = 2
    count = 2

  • At decimalN = 2

    Inside while loop,

    rem = 0
    c = 100
    binaryN = 10

    Now, decimalN = 1
    count = 3

  • At decimalN = 1

    Inside while loop,

    rem = 1
    c = 1000
    binaryN = 1010

    Now, decimalN = 0
    count = 4

  • At decimalN = 0 , (decimalN != 0) is false. So, while loop is terminated.

Finally, value in binaryN is our resultant binary number for decimal number 10.

Note – It won’t work for large decimal number. If you want to convert large number you need to change data type in above code.
Or, you can use inbuilt library function to convert decimal to binary.

2. Using toBinaryString() function to Convert Decimal to Binary

We can use Integer.toBinaryString() function to convert decimal to binary number.

import java.util.*

fun main() {
    val read = Scanner(System.`in`)

    println("Enter n:")
    val decimalN = read.nextInt()

    val binaryResult = Integer.toBinaryString(decimalN)

    println("Equivalent Binary: $binaryResult")
}

When you run the program, output will be –

Enter n:
999999999
Equivalent Binary: 111011100110101100100111111111

Thus, we went through kotlin program to convert decimal number to binary number.

Leave a Reply