Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to integer hex value "Strange" behaviour

Tags:

java

I have noticed java will not allow me to store large numbers such as 2000000000, i.e 2 billion obviously to an integer type, but if I store the corresponding hex value i.e int largeHex = 0x77359400; this is fine,

So my program is going to need to increment up to 2^32, just over 4.2 billion, I tested out the hex key 0xffffffff and it allows me to store as type int in this form,

My problem is I have to pull a HEX string from the program.

Example

sT = "ffffffff";

int hexSt = Integer.valueOf(sT, 16).intValue();

this only works for smaller integer values

I get an error

Exception in thread "main" java.lang.NumberFormatException: For input string: "ffffffff"

All I need to do is have this value in an integer variable such as

int largeHex = 0xffffffff

which works fine?

I'm using integers because my program will need to generate many values.

like image 665
user524156 Avatar asked Dec 09 '22 12:12

user524156


2 Answers

String hex = "FFFFFFFF"; // or whatever... maximum 8 hex-digits
int i = (int) Long.parseLong(hex, 16);

Gives you the result as a signed int ...

like image 80
Rop Avatar answered Feb 12 '23 13:02

Rop


Well, it seems there is nothing to add to the answers, but it's worth it to clarify:

  • It throws an exception on parsing, because ffffffff is too big for an integer. Consider Integer.parseInt(""+Long.MAX_VALUE);, without using hex representation. The same exception is thrown here.
  • int i = 0xffffffff; sets i to -1.
  • If you already decided to use longs instead of ints, note that long l = 0xffffffff; will set l to -1 as well, since 0xffffffff is treated as an int. The correct form is long l = 0xffffffffL;.
like image 35
khachik Avatar answered Feb 12 '23 12:02

khachik