Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing big hexadecimal numbers in Java

I'm trying to parse into int a String which is hexadecimal number in my code (FF00FF00, for example) using Integer.parseInt(String string, int radix), but always get NumberFormatException. If I parse the number without last two numbers (FF00FF) it works well.

Is there any method to parse such big numbers in Java?

like image 395
teoREtik Avatar asked Mar 09 '26 09:03

teoREtik


2 Answers

If Integer is too small, use Long:

Long.parseLong(string, 16)

If Long is still too small, use BigInteger:

new BigInteger(string, 16)
like image 169
Sean Patrick Floyd Avatar answered Mar 10 '26 23:03

Sean Patrick Floyd


I would use Long.parseLong(x, 16) BigInteger is overkill for a 32-bit value.

If you expect this value to be an int value you can cast the result.

int x = (int) Long.parseLong("FF00FF00", 16);
like image 41
Peter Lawrey Avatar answered Mar 11 '26 00:03

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!