How do I parse a hex-int from a string to an Integer?

◇◆丶佛笑我妖孽 提交于 2019-12-25 03:49:38

问题


I have no problem in writing this: (it also doesn't give any errors)

int hex = 0xFFFFFFFF;

The integer has to have an alpha value also!

But when I try to do this:

Integer hex = Integer.parseInt("0xFFFFFFFF");
// Or I try this:
Integer hex = Integer.parseInt("FFFFFFFF");

I get a java.lang.NumberFormatException: For input string: "0xFFFFFFFF" thrown!

Why is this not working?

I'm guessing that there is some other way to parse hex integers that I am just not realizing, and I really need to be able to parse hex from string for a program I am making.


回答1:


There is actually a separate function where you can define the radix:

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int)

Integer.parseInt(x) simply calls Integer.parseInt(x, 10), so you have to specify a radix 10 number.

In order to parse a hex string, you would simply have to use the following (note that the 0x prefix is not allowed):

Integer.parseInt("FFFFFFF", 16);


来源:https://stackoverflow.com/questions/27066487/how-do-i-parse-a-hex-int-from-a-string-to-an-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!