Convert decimal number to binary in Kotlin

PROBLEM

Given a number in the decimal system, convert it to the binary system. From base 10 to base 2.

Solution

One solution is to keep dividing the given decimal number by 2 and checking its quotient [1]. For example:

class Binary {

    fun convertDecimal(decimal: Long): String {

        var binary = ""
        var res: Long = decimal

        while (res != 0L) {
            binary = (res  % 2L ).toString() + binary
            res /= 2
        }

        return binary.padStart(8,'0')
    }
}

The code above will return a String representing the binary number and if its length is less than 8 bits then it is filled with 0s.

Let’s convert numbers from 1 to 50:

fun main() {
    for (i in 1..50)
        println( i.toString() + " -> " +Binary().convertDecimal(i.toLong()))

The output will be:

 1 -> 00000001
 2 -> 00000010
 3 -> 00000011
 4 -> 00000100
 5 -> 00000101
 6 -> 00000110
 7 -> 00000111
 8 -> 00001000
 9 -> 00001001
 10 -> 00001010
 11 -> 00001011
 12 -> 00001100
 13 -> 00001101
 14 -> 00001110
 15 -> 00001111
 16 -> 00010000
 17 -> 00010001
 18 -> 00010010
 19 -> 00010011
 20 -> 00010100
 21 -> 00010101
 22 -> 00010110
 23 -> 00010111
 24 -> 00011000
 25 -> 00011001
 26 -> 00011010
 27 -> 00011011
 28 -> 00011100
 29 -> 00011101
 30 -> 00011110
 31 -> 00011111
 32 -> 00100000
 33 -> 00100001
 34 -> 00100010
 35 -> 00100011
 36 -> 00100100
 37 -> 00100101
 38 -> 00100110
 39 -> 00100111
 40 -> 00101000
 41 -> 00101001
 42 -> 00101010
 43 -> 00101011
 44 -> 00101100
 45 -> 00101101
 46 -> 00101110
 47 -> 00101111
 48 -> 00110000
 49 -> 00110001
 50 -> 00110010
Conclusion

This is one approach of calculating a binary number. Algorithm as found on this website.

See more Kotlin tutorials

References
[1] https://www.rapidtables.com/convert/number/decimal-to-binary.html


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x