Given a Binary Number as Input. Now, write a Kotlin Program to Convert Binary Number to equivalent decimal number.
Input: 100 Output: 4
Input: 110 Output: 6
Input: 101 Output: 5
1. Program to Convert Binary to Decimal
Pseudo Algorithm
- Initialise a variable decimalNum, that stores equivalent decimal value, with 0
- Extract each digit from the given binary number.
- While extracting, multiply the extracted digit with proper base (power of 2).
- For example, if binary number is 110, decimalNum = 1 * (2^2) + 1 * (2^1) + 0 * (2^0) = 6
Sourcecode –
import java.util.*
fun main() {
val read = Scanner(System.`in`)
println("Enter n:")
val binaryN = read.nextLong()
var decimalNum: Long = 0
if(checkBinary(binaryN)) {
var n = binaryN
var base = 1
while (n != 0.toLong()) {
val lastDigit = n % 10
n /= 10
decimalNum += lastDigit * base
base *= 2
}
println("Equivalent Decimal : $decimalNum")
} else {
println("$binaryN is not a binary number")
}
}
private fun checkBinary(binaryNum: Long): Boolean {
var isBinary = true
var n = binaryNum
while (n != 0.toLong()) {
val lastDigit = n % 10
if(!((lastDigit == 0.toLong()) || (lastDigit == 1.toLong()))) {
isBinary = false
break
}
n /= 10
}
return isBinary
}
When you run the program, output will be –
Enter n: 100010 Equivalent Decimal : 34
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.nextLong() means read anything entered by user before space or line break from standard input – Keyboard.
We stored value entered by user in variable binaryN.
At first, we checked if entered value is binary or not.
If NO, we print a message ” number is not binary number”.
- We use checkBinary function to check if number is binary or not. If any digit in number is neither 0 nor 1, then, it is not binary number.
If Yes, we start converting those number into decimal –
- variable base contains power of 2 to the position at which current last digit we have in lastDigit
- Decimal value is sum of lastDigit * (power of 2 to the position at which current lastDigit is at)
- For example,
binaryN = 110decimalN = 1 * (2 ^ 2) + 1 * (2^1) + 1 * (2 ^ 0) = 6
Thus, we went through Kotlin program to convert binary number to equivalent decimal number.