Parse a binary string as a number in Kotlin
This article explores different ways to parse a binary string as a number in Kotlin.
A simple solution to parse the string as a number in the specified radix is using the toInt() function. This is demonstrated below:
|
1 2 3 4 5 6 |
fun main() { val binary = "11111111" val i = binary.toInt(2) println(i) // 255 } |
The maximum value that can be parsed by the toInt() function is 231-1 (01111111 11111111 11111111 11111111 in binary), as shown below:
|
1 2 3 4 5 6 |
fun main() { val binary = "01111111111111111111111111111111" val i = binary.toInt(2) println(i) // 2147483647 } |
To parse the binary string 11111111 11111111 11111111 11111111 which represent the decimal value -1, use the Integer.parseUnsignedInt() function:
|
1 2 3 4 5 6 |
fun main() { val binary = "11111111111111111111111111111111" val i = Integer.parseUnsignedInt(binary, 2) println(i) // -1 } |
Alternatively, the toLong() function can be used in the following manner:
|
1 2 3 4 5 6 |
fun main() { val binary = "11111111111111111111111111111111" val i = binary.toLong(2).toInt() println(i) // -1 } |
Finally, we can write a custom method to convert a binary string to a decimal. It can be implemented as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import kotlin.math.pow fun toInteger(binary: String): Int { var decimal: Long = 0 for (i in binary.length - 1 downTo 0) { if (binary[i] == '1') { decimal += 2.0.pow((binary.length - i - 1).toDouble()).toLong() } } return decimal.toInt() } fun main() { val binary = "11111111111111111111111111111111" val i = toInteger(binary) println(i) // -1 } |
That’s all about parsing a binary string as a number 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 :)