Kotlin Program to Convert Large Binary Number to Decimal

Given a Large Binary Number as Input. Now, write a Kotlin Program to Convert Large Binary Number to decimal number.

Input:
110000000000000111111

Output:
Equivalent decimal: 1572927

1. Program to Convert Binary to Decimal

Pseudo Algorithm
  • Key Idea is to use string for input instead of int type, and Long for Output just to increase the range of output.
  • Initialise a variable decimalVal, that stores equivalent decimal value, with 0
  • Extract each character from the string.
  • While extracting, check if character is 1. If yes, multiply the extracted character with proper base (power of 2).
  • For example, if binary number is 110, decimalVal = 1 * (2^2) + 1 * (2^1) = 6

Sourcecode –

fun main() {

    println("Enter n:")
    val binaryN = readLine()

    val countDigit = binaryN!!.length -1

    var decimalVal: Long = 0

    var base = 1
    for(pos in countDigit downTo 0) {
        val curChar = binaryN[pos]
        if(curChar == '1') {
            decimalVal += base
        }
        base *= 2

        if(!(curChar == '1' || curChar == '0')) {
            decimalVal = -1
            println("$binaryN is not binary number.")
            break
        }
    }

    if(decimalVal != (-1).toLong()) {
        println("Equivalent decimal: $decimalVal")
    }
}

When you run the program, output will be –

Enter n:
110000000000000000000000
Equivalent decimal: 12582912
Explanation:
  • Run a loop from end to first character of the string.
  • At each position, check if character at that position is 1. If yes, add base in decimalVal.
  • Note that base value is calculated for each position. If you observe carefully, base is actually power of 2 for each position in the string.
  • Finally, at postion = 0, we get final decimal value.
  • Note that we also check, at every position, if character is 0 or 1. It is neither 0 nor 1, it means given string is not binary. So, print error message.

Thus, we went through Kotlin Program to Convert Large Binary Number to Decimal Number

Leave a Reply