开发者

Converting string to integer hex value "Strange" behaviour

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.


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

Gives you the result as a signed int ...


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;.


How about using:


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

Which outputs:

4294967295


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 =)


Consider using BigInteger

http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜