Chris Stewart
Chris Stewart

Reputation: 1689

Parse signed number from hex using BigInt

I'm trying to parse a signed number using a BigInt. Here have been my attempts

scala> -1.toHexString
res7: String = ffffffff

scala> val bigInt = BigInt(res7,16)
bigInt: scala.math.BigInt = 4294967295

Is there any way to easily parse a signed number from a hex using BigInt?

Upvotes: 1

Views: 492

Answers (2)

Keith Pinson
Keith Pinson

Reputation: 1725

If your hex string began life as an Integer or a Long—before converting it to a BigInt—parse it as an unsigned number with

java.lang.Integer.parseUnsignedInt("ffffffff",16)  // Results in -1

or

java.lang.Long.parseUnsignedLong("ffffffffffffffff",16)  // Results in -1

Upvotes: 1

Dima
Dima

Reputation: 40500

You have to tell it how long your number is one way or another. Without it, just saying "ffffffff" is ambiguous: as an Int it is -1, but as a long it is a large positive value:

 bigInt.toLong
 res48: Long = 4294967295

 bigInt.toInt
 res49: Int = -1

Upvotes: 0

Related Questions