Kotlin Program to Convert HexaDecimal Number to Binary

Given an HexaDecimal number as input. Now, write a Kotlin program to convert HexaDecimal number to Binary.

Input:
7

Output:
111
Input:
120

Output:
001010000
Input:
A1

Output:
10100001

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 –

fun main() {

    println("Enter n:")
    val hexaDecimalN = readLine()!!

    if(checkHexaDecimalNumber(hexaDecimalN)) {

        var i = 0
        var binaryNum = ""
        while(i < hexaDecimalN.length) {
            when(hexaDecimalN[i]) {
                '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"
            }
            i++
        }
        println("Equivalent Binary : $binaryNum")
    } else {
        println("$hexaDecimalN is not a hexaDecimal number")
    }
}

private fun checkHexaDecimalNumber(hexaDecimalNum: String): Boolean {
    var isHexaDecimalNum = true

    for(charAtPos in hexaDecimalNum) {
        if(!(
                       ((charAtPos >= '0') && (charAtPos <= '9'))
                    || ((charAtPos >= 'A') && (charAtPos <= 'F'))
                    || ((charAtPos >= 'a') && (charAtPos <= 'f'))
            )) {
            isHexaDecimalNum = false
            break
        }
    }
    return isHexaDecimalNum
}

When you run the program, output will be –

Enter n:
12
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.

Leave a Reply