Given an HexaDecimal number as input. Now, write a Kotlin program to convert HexaDecimal number to Binary.
1. Program to Convert HexaDecimal to Binary
Pseudo Algorithm
- Initialize a variable binaryNum with empty string.
- Now, convert each digit of hexaDecimal number into binary and append it to binaryNum.
- Repeat till last digit of the hexaDecimal number.
- Finally, binaryNum will contain binary representation of hexaDecimal number.
Sourcecode –
val hexaDecimalN = readLine()!! |
if (checkHexaDecimalNumber(hexaDecimalN)) { |
while (i < hexaDecimalN.length) { |
'0' -> binaryNum += "0000" |
'1' -> binaryNum += "0001" |
'2' -> binaryNum += "0010" |
'3' -> binaryNum += "0011" |
'4' -> binaryNum += "0100" |
'5' -> binaryNum += "0101" |
'6' -> binaryNum += "0110" |
'7' -> binaryNum += "0111" |
'8' -> binaryNum += "1000" |
'9' -> binaryNum += "1001" |
'A' , 'a' -> binaryNum += "1010" |
'B' , 'b' -> binaryNum += "1011" |
'C' , 'c' -> binaryNum += "1100" |
'D' , 'd' -> binaryNum += "1101" |
'E' , 'e' -> binaryNum += "1110" |
'F' , 'f' -> binaryNum += "1111" |
println( "Equivalent Binary : $binaryNum" ) |
println( "$hexaDecimalN is not a hexaDecimal number" ) |
private fun checkHexaDecimalNumber(hexaDecimalNum: String): Boolean { |
var isHexaDecimalNum = true |
for (charAtPos in hexaDecimalNum) { |
((charAtPos >= '0' ) && (charAtPos <= '9' )) |
|| ((charAtPos >= 'A' ) && (charAtPos <= 'F' )) |
|| ((charAtPos >= 'a' ) && (charAtPos <= 'f' )) |
When you run the program, output will be –
Equivalent Binary : 00010010 |
Explanation:
We just extract each digit from the original hexaDecimal number. Then, we converted that digit into binary and appended it with binaryNum
variable. Finally, binaryNum contains binary representation of the hexaDecimal number.
Note that we have used 4 digits binary number for each digit of hexaDecimal number. Can you tell me why?
Let me know in the comment section 
Thus, we went through Kotlin Program to Convert HexaDecimal Number to Binary Number.