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:

Download Code

 
The maximum value that can be parsed by the toInt() function is 231-1 (01111111 11111111 11111111 11111111 in binary), as shown below:

Download Code

 
To parse the binary string 11111111 11111111 11111111 11111111 which represent the decimal value -1, use the Integer.parseUnsignedInt() function:

Download Code

 
Alternatively, the toLong() function can be used in the following manner:

Download Code

 
Finally, we can write a custom method to convert a binary string to a decimal. It can be implemented as follows:

Download Code

That’s all about parsing a binary string as a number in Kotlin.