Alexey
Alexey

Reputation: 3192

Kotlin NumberFormatException

Why "b23c77126dd924bf".toLong(16) produces java.lang.NumberFormatException ??

As of official docs, Long "Represents a 64-bit signed integer"

And 0xb23c77126dd924bf fits in 64 bits, it is decimal -5603472915319675713

Upvotes: 0

Views: 1049

Answers (2)

Ekeko
Ekeko

Reputation: 1981

The problem here is that if you don't explicitly prepend the - sign before a Kotlin literal, then the literal is always assumed to represent a positive number. So here 0xB23C77126DD924BF is not interpreted according to its two's-complement representation, which would give you -5603472915319675713 if you assume it's a 64 signed integer. It is interpreted as 12843271158389875903, which is outside of Long supported range.

This is the same question as Java Integer.MAX_VALUE vs Kotlin Int.MAX_VALUE, but here it's related to Long instead of Int.

Upvotes: 1

Sasi Kumar
Sasi Kumar

Reputation: 13278

Its working .Use BigInteger

        val numb = "b23c77126dd924bf"
        val res = BigInteger(numb, 16)
        println(res)     //12843271158389875903
        println(res.toLong()) //-5603472915319675713

Upvotes: 0

Related Questions