I'm using Kotlin on Linux (kotlinc-jvm 1.7.21)
I would like to store a large number in a variable. So I found ULong to store 64 bits numbers.
My number in binary is : 1111100001111100001111100001111110001111110001111110001111110001
. This is 64 bits long, so just under the limit of a ULong variable.
However, when I try to convert it from String to ULong,
var myLargeNumber = "1111100001111100001111100001111110001111110001111110001111110001".toULong()
I have the error :
Exception in thread "main" java.lang.NumberFormatException: Invalid number format: '1111100001111100001111100001111110001111110001111110001111110001'
CodePudding user response:
myLargeNumber.toULong()
will try to interpret the number in base 10. 1111100001111100001111100001111110001111110001111110001111110001
is a lot larger than the maximum ULong
value of 18446744073709551615
, so toULong()
fails
To interpret the number as a binary number you can instead specify the radix:
fun main() {
val myLargeNumber = "1111100001111100001111100001111110001111110001111110001111110001"
.toULong(radix = 2) // treat the string as a base 2 number
println(myLargeNumber)
// output: 17905254523795399665
}