Kotlin program to convert binary to decimal

Kotlin | Converting Binary to Decimal: Here, we are going to learn how to convert binary number system to decimal number system in Kotlin programming language? Submitted by IncludeHelp, on April 20, 2020

Problem statement

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

Example:

Input:
Binary value: 110010

Output:
Decimal value: 50

Kotlin - Convert binary to decimal

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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.