Converting string to integer hex value "Strange" behaviour

3

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.

java
asked on Stack Overflow Dec 4, 2010 by user524156 • edited Dec 4, 2018 by ZachB

6 Answers

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

Gives you the result as a signed int ...

answered on Stack Overflow Dec 29, 2012 by Rop • edited Dec 30, 2012 by Rop
2

How about using:


System.out.println(Long.valueOf("ffffffff", 16).longValue());

Which outputs:

4294967295
answered on Stack Overflow Dec 4, 2010 by Jiri Patera
2

The int data type, being signed will store values up to about 2^31, only half of what you need. However, you can use long which being 64 bits long will store values up to about 2^63.

Hopefully this will circumvent your entire issue with hex values =)

answered on Stack Overflow Dec 4, 2010 by gsteinert • edited Dec 4, 2010 by cHao
2

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;.
answered on Stack Overflow Dec 4, 2010 by khachik • edited Aug 15, 2013 by arshajii
0
0

int test = 0xFFFFFF; int test2 = Integer.parseInt(Integer.toHexString(test), 16);

^---That works as expected... but:

int test = 0xFFFFFFFF; int test2 = Integer.parseInt(Integer.toHexString(test), 16);

^--That throws a number format exception.

int test = 0xFFFFFFFF; int test2 = (int)Long.parseLong(Integer.toHexString(test), 16);

^--That works fine.

answered on Stack Overflow Mar 26, 2013 by Richard Smith

User contributions licensed under CC BY-SA 3.0