1. Introduction

Sometimes, developers need to find solutions to problems that involve binary operations or binary numbers. This can include requiring developers to convert between decimal and binary numbers.

In this article, we’ll explore different ways we can convert binary numbers to decimal numbers and vice versa using Kotlin.

2. Converting From Binary Numbers to Decimal

In this section, we’ll look at a few ways to convert binary numbers to decimals.

First, let’s clarify what binary and decimal numbers are. A binary number is a base 2 number that is composed of digits 0-1.

On the other hand, a decimal number is a base 10 number composed of digits 0-9.

2.1. Binary to Decimal Algorithm

Let’s look at an algorithm that converts a binary number to a decimal number.

First, we’ll reverse our binary string. This will allow us to easily iterate the digits from right to left, while we increase our counter tracking the positional index of the bit.

While we iterate the binary string in reverse order, we’ll calculate the decimal contribution for each bit by multiplying the bit by 2^i, where i is the bit’s positional index. We can add the result of each of these multiplications together for the final result:

fun binaryToDecimal(binary: String): Int{
    val reversedDigits = binary.reversed().toCharArray().map{it.digitToInt()}
    var decimalNumber = 0
    var i = 0

    for (n in reversedDigits) {
        decimalNumber += (n * 2.0.pow(i)).toInt()
        ++i
    }
    return decimalNumber
}

Now, we can test our function:

@Test
fun `binary to decimal mathematical approach`(){
    assertEquals(439, binaryToDecimal("110110111"))
    assertEquals(109, binaryToDecimal("1101101"))
    assertEquals(27, binaryToDecimal("11011"))
    assertEquals(122979, binaryToDecimal("11110000001100011"))
    assertEquals(12, binaryToDecimal("1100"))
    assertEquals(98, binaryToDecimal("1100010"))
}

2.2. Using toInt() With Radix Method

Alternatively, a simple way to convert a binary number to decimal is to use the default toInt() method on our binary string.

When using this conversion method, it’s important to account for the radix (or base) of the integer that the String represents when the String does not represent a base 10 number. Consequently, to convert such values, we must pass the radix as the optional argument for toInt(). So, in our case, since a binary number is base 2, we need to pass 2 as the radix or base:

@Test
fun `binary to decimal using toInt() method`(){
    assertEquals(439, "110110111".toInt(2))
    assertEquals(109, "1101101".toInt(2))
    assertEquals(27, "11011".toInt(2))
    assertEquals(122979, "11110000001100011".toInt(2))
    assertEquals(12, "1100".toInt(2))
    assertEquals(98, "1100010".toInt(2))
}

3. Converting From Decimal Numbers to Binary

Finally, let’s look at the other side of this problem – converting from decimal numbers to binary.

3.1. Decimal to Binary Using List

We’ll use a list to track each digit we compute, before joining the list together for our final number.

While we iterate, we’ll divide the decimalNumber by 2 and store the remainder in a list. Each of these remainders represents a bit in our binary number. Secondly, we divide the decimalNumber by 2 and update its value. We keep doing these steps while the decimalNumber is greater than zero.

Since our algorithm is using division to extract digits from the right side of the decimal number, reversing the order of the items in our list will yield the final binary number equivalent of the decimal number:

fun decimalToBinary(n: Int): String {
    val intList = mutableListOf<Int>()
    var decimalNumber = n
    var result = ""
    var i = 0

    while (decimalNumber > 0) {
        intList.add(decimalNumber % 2)
        decimalNumber /= 2
    }
    return intList.reversed().joinToString("")
}

Finally, let’s test our custom method:

@Test
fun `decimal to binary mathematical approach`(){
    assertEquals("110110111", decimalToBinary(439))
    assertEquals("1101101", decimalToBinary(109))
    assertEquals("11011", decimalToBinary(27))
    assertEquals("1100", decimalToBinary(12))
    assertEquals("1100010", decimalToBinary(98))
}

3.2. Using Integer.toBinaryString() Method

Alternatively, another straightforward method we can use to convert a decimal number to binary is by using Integer.toBinaryString(). It’s included by default in Java, which we can leverage in Kotlin.

Ultimately, this approach allows us to pass our number to the built-in conversion function directly:

@Test
fun `decimal to binary using toBinaryString() method`(){
    assertEquals("110110111", Integer.toBinaryString(439))
    assertEquals("1101101", Integer.toBinaryString(109))
    assertEquals("11011", Integer.toBinaryString(27))
    assertEquals("1100", Integer.toBinaryString(12))
    assertEquals("1100010", Integer.toBinaryString(98))
}

4. Conclusion

To sum up, we’ve explored different ways to convert from a binary number to a decimal number and vice versa. We looked at custom approaches that involve running through an algorithm to achieve the desired results, and we also looked at interesting default methods such as toInt() and Integer.toBinaryString() methods.

As always, the code samples and relevant test cases for this article can be found over on GitHub.