Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; SEOFriendlyImages has a deprecated constructor in /home/tutorig3/public_html/wp-content/plugins/seo-image/seo-friendly-images.class.php on line 2

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in /home/tutorig3/public_html/wp-content/themes/mts_interactive/options/php-po/php-po.php on line 185
Kotlin Program to Convert Large Binary Number to Decimal - Tutorialwing

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