Kotlin Programming Cookbook
上QQ阅读APP看书,第一时间看更新

Parsing string to Long with special radix

In the preceding examples, we were parsing strings with radix 10, that is, decimals. By default, the radix is taken as 10, but there are certain situations where we need different radix. For example, in case of parsing a string into a binary or octal number. So now, we will see how to work with radix other than the decimal. Though you can use any valid radix, we will show examples that are most commonly used, such as binary and octal.

  • Binary: Since a binary number is made from 0 and 1, the radix used is 2:
fun main(args: Array<String>) {
val str="11111111"
print(str.toLongOrNull(2)) }

On running the preceding program, the following output is generated:

 255
  • Octal: The octal numeral system, or oct for short, is the base-8 number system and uses the digits 0 to 7. Hence, we will use 8 as a radix:
fun main(args: Array<String>) {
val str="377"
print(str.toLongOrNull(8))
}

On running the preceding program, this output is generated:

 255
  • Decimal: The decimal system has 10 numbers in it (0-9); hence, we will use 10 as radix. Note that radix as 10 is used by default in the methods without the radix arguments (.toLong() , .toLongOrNull()):
fun main(args: Array<String>) {
val str="255"
print(str.toLongOrNull(10))
}

On running the preceding program, the following output is generated:

 255