Convert an integer to a binary string in Kotlin
This article explores different ways to convert an integer to a binary string of a specific length in Kotlin. The solution should left-pad the binary string with leading 0’s.
1. Using Integer.toBinaryString() function
The standard way to get a binary string from an integer is with Integer.toBinaryString(). To get a binary string of a specific length with leading 0’s, you can take the help of String.format() with the replace() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun toBinary(x: Int, len: Int): String { return String.format( "%" + len + "s", Integer.toBinaryString(x) ).replace(" ".toRegex(), "0") } fun main() { var num = 10000 var len = 16 println(toBinary(num, len)) // 0010011100010000 } |
2. Using StringBuilder
You can also write your own routine for converting an integer to a binary string of a specific length with leading 0’s.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun toBinary(x: Int, len: Int): String { val result = StringBuilder() for (i in len - 1 downTo 0) { val mask = 1 shl i result.append(if (x and mask != 0) 1 else 0) } return result.toString() } fun main() { var num = 10000 var len = 16 println(toBinary(num, len)) // 0010011100010000 } |
3. Using Character Array
Alternatively, you can use a character array instead of a StringBuilder.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun toBinary(x: Int, len: Int): String { val buffer = CharArray(len) for (i in len - 1 downTo 0) { val mask = 1 shl i buffer[len - 1 - i] = if (x and mask != 0) '1' else '0' } return String(buffer) } fun main() { var num = 10000 var len = 16 println(toBinary(num, len)) // 0010011100010000 } |
That’s all about converting an integer to a binary string 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 :)