-2

I attempted the following command in Scala and get a NumberFormatException, but I am not sure why. It may be something elementary, but I would certainly appreciate an extra set of eyes. Thank you so much!

"11111000000000000000".toLong

java.lang.NumberFormatException: For input string: "11111000000000000000" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:592) at java.lang.Long.parseLong(Long.java:631) at scala.collection.immutable.StringLike$class.toLong(StringLike.scala:276) at scala.collection.immutable.StringOps.toLong(StringOps.scala:30)
... 33 elided

SamTh3D3v
  • 9,854
  • 3
  • 31
  • 47
jax
  • 19

3 Answers3

6

The method

Long.parseLong(String s)

parses the string argument as a signed decimal long (uses radix of 10). 11111000000000000000, when treated as a base 10 number is larger than the maximum value of Long, which is why the java.lang.NumberFormatException is being thrown.

Chances are you're looking for

Long.parseLong("11111000000000000000", 2)

which treats the number as binary (base 2).

Otherwise you may want to check out java.math.BigInteger which can handle arbitrary precision integers.

AtomHeartFather
  • 954
  • 17
  • 35
3
 9223372036854775807 // maximum value of Long
11111000000000000000 // your value

Notice something?

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
2

long range for 64bit

–9,223,372,036,854,775,808 to

 9 ,223,372,036,854,775,807

or use BigInteger ex: Using the constructor

String val="111110000000000000000"

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

reference: BigInteger or not BigInteger?

String to BigInteger java

Community
  • 1
  • 1
Piyush Mittal
  • 1,860
  • 1
  • 21
  • 39