Q:

Kotlin program to convert binary to decimal

belongs to collection: Kotlin Basic Programs

0

Given a binary number, we have to convert it into decimal number.

Example:

    Input:
    Binary value: 110010

    Output:
    Decimal value: 50

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In the below program, we are taking a binary value and converting it to the equivalent decimal number system.

Take an example,

    The binary number is: 110010
    Conversion logic: Take digits from right
    decimal  = 0
    decimal += 0*2^0 =  0 +  0 =  0
    decimal += 1*2^1 =  0 +  2 =  2
    decimal += 0*2^2 =  2 +  0 =  2
    decimal += 0*2^3 =  2 +  0 =  2
    decimal += 1*2^4 =  2 + 16 = 18
    decimal += 1*2^5 = 18 + 32 = 50

Program to convert binary to decimal in Kotlin

package com.includehelp.basic

import java.util.*

/**
* to check is given number is binary number or not
* @param binaryNumber
* @return
*/
fun isBinaryNumber(binaryNumber: Long): Boolean {
    var binaryNumber = binaryNumber
    
    while (binaryNumber > 0) {
        if (binaryNumber % 10 > 1) {
            return false
        }
        binaryNumber = binaryNumber / 10
    }
    return true
}


/**
* to get Decimal number from input binary number
* @param binaryNumber
* @return
*/
fun getDecimalNumber(binaryNumber: Long): Int {
    var binaryNumber = binaryNumber
    var decimalNo = 0
    var power = 0
    
    while (binaryNumber > 0) {
        val r = binaryNumber % 10
        decimalNo = (decimalNo + r * Math.pow(2.0, power.toDouble())).toInt()
        binaryNumber /= 10
        power++
    }
    return decimalNo
}

// Main Method Entry Point of Program
fun main(arg: Array<String>) {
    val sc = Scanner(System.`in`)
    
    // Input Binary Number
    println("Enter Binary Number  : ")      
    val binaryNmber: Long = sc.nextLong()
    
    // Condition to check given no is Binary 
    // or not call isBinary Method
    if (isBinaryNumber(binaryNmber)) {
        // Call function for Convert binary number into Decimal
        val decimalNumber: Int = getDecimalNumber(binaryNmber)  
        // Print Decimal Number
        println("Decimal Number : $decimalNumber")              
    } else {
        println("Number is not Binary")
    }
}

Output

Run 1:
Enter Binary Number  :
101011
Decimal Number : 43
-----
Run 2:
Enter Binary Number  :
1011
Decimal Number : 11
----
Run 3:
Enter Binary Number  :
10101002
Number is not Binary
----
Run 4:
Enter Binary Number  :
10101011001010101
Decimal Number : 87637

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Kotlin program to convert octal number to binary n... >>
<< Kotlin program to convert binary number to octal n...