Convert a decimal number to binary in Kotlin
This article explores different ways to convert a decimal number to binary in Kotlin.
A simple solution to get the binary representation of an integer in string format is using the toBinaryString() function from the Integer class.
|
1 2 3 4 5 6 7 |
fun main() { val n: Int = 75 val binary: String = Integer.toBinaryString(n) println(binary) // 1001011 } |
The Int.toString() function also returns the string representation of a non-negative integer in the specified radix. We can use it as:
|
1 2 3 4 5 6 7 |
fun main() { val n = 75 val binary = n.toString(2) println(binary) // 1001011 } |
Alternately, we can use the Long.toBinaryString() function for long value.
|
1 2 3 4 5 6 7 |
fun main() { val n: Long = 75 val binary: String = java.lang.Long.toBinaryString(n) println(binary) // 1001011 } |
Finally, we can write custom logic to convert an integer to binary format, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun toBinary(n: Int): String { return if (n != 0) toBinary(n / 2) + n % 2 else { "" } } fun main() { val n = 75 val binary = toBinary(n) println(binary) // 00000000000000000000000001001011 } |
That’s all about converting a decimal number to binary in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)