0

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

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.