Witold Strumiński
Witold Strumiński

Reputation: 3

How to change very long String to Integer

How to make this work?

long l = Long.valueOf(Integer.parseInt(DatatypeConverter.printHexBinary(myBytes), 16));
textField.setText("" + l);

It is throwing NumberFormatException because it is too long.

Upvotes: 0

Views: 259

Answers (2)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79807

Your problem may be that you're trying to convert your number first to an int, then afterwards to a long. This will only work for numbers up to about 2 billion, because that's the biggest number that fits in an int.

If your number will fit in a long (up to about 19 digits), but not an int, then you should be using the parseLong method of the Long class, instead of parseInt.

long myLong = Long.parseLong(myHexString, 16);

However, if the value is too big for a long, you'll need the BigInteger class.

BigInteger myInteger = new BigInteger(myHexString, 16);

Choose carefully. long values tend to perform much better than BigInteger values, so if you know that there's no chance your value will exceed the largest possible long, then you may wish to choose long.

Upvotes: 3

Aman Chhabra
Aman Chhabra

Reputation: 3894

Please use BigInteger for such cases. It is slow in performance, but solves the purpose perfectly

There is a constructor of BigInteger which accepts String and create instance with value passed as String:

BigInteger(String val)

You can follow the documentation here: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html

Upvotes: 1

Related Questions