Write a Kotlin Program to Convert Binary Number to Decimal and vice-versa

Binary to Decimal Conversion

To convert a binary number to decimal, we can use the toInt(radix: Int) function.

The radix parameter specifies the base of the number we want to convert. In this case, we set it to 2 to indicate that the input is a binary number.

Here is an example Kotlin program that converts a binary number to decimal:

fun binaryToDecimal(binary: String): Int {
    return binary.toInt(2)
}

fun main() {
    val binaryNumber = "101010"
    val decimalNumber = binaryToDecimal(binaryNumber)
    println("Binary number $binaryNumber is equal to decimal number $decimalNumber")
}

Output: Binary number 101010 is equal to decimal number 42

Decimal to Binary Conversion

To convert a decimal number to binary, we can use the toString(radix: Int) function.

The radix parameter specifies the base of the number we want to convert to. In this case, we set it to 2 to indicate that we want to convert the decimal number to a binary number.

Here is an example Kotlin program that converts a decimal number to binary:

fun decimalToBinary(decimal: Int): String {
    return decimal.toString(2)
}

fun main() {
    val decimalNumber = 42
    val binaryNumber = decimalToBinary(decimalNumber)
    println("Decimal number $decimalNumber is equal to binary number $binaryNumber")
}

Output: Decimal number 42 is equal to binary number 101010

In conclusion, Kotlin makes it easy to convert binary numbers to decimal and vice versa using built-in functions.

With these examples, you can easily implement binary and decimal conversion in your Kotlin programs.