Home > OS >  converting a string to int in kotlin There is a problem
converting a string to int in kotlin There is a problem

Time:02-12

why result is mines? my problem is converting a string to int in kotlin .

class Test{
    val x="200000000"
    val y="11"
}


fun main(){
    val test=Test()
    println(test.x.toInt())
    println(test.y.toInt())
    val z=(Integer.parseInt(test.x))*(Integer.parseInt(test.y))
//or :val z=(test.x.toInt())*(test.y.toInt())
    println(z)

}

result :

200000000

11

-2094967296

CodePudding user response:

You're witnessing an integer overflow.

Int in Kotlin (like in Java) represents 32-bit signed integers, so their maximum value is 2,147,483,647.

What you're trying to do is multiply 200,000,000 by 11, which would yield 2,200,000,000 - more than the maximum value. So only the least significant bits of that number can be stored in the 32-bit of the integer, and you end up somewhere in the negative numbers.

If you want to reach this kind of values, you should either use UInt (unsigned integers, which can go twice higher), Long (which are 64-bit and thus can reach much much higher), or other more complex types like BigInteger.

Here is an example with Long:

val x = "200000000"
val y = "11"
val z = x.toLong() * y.toLong()
println(z) // 2200000000
  • Related