将十六进制字符串解析为Integer会抛出NumberFormatException? [英] Parsing a Hexadecimal String to an Integer throws a NumberFormatException?
问题描述
int hex = 0x00ff00;
我认为你应该能够扭转这个过程。我有这样的代码:
Integer.valueOf(primary.getFullHex());
其中primary是自定义Color类的对象。它的构造函数需要一个Integer来指定不透明度(0-99)和一个十六进制字符串(例如 00ff00
)。
是 getFullHex
方法:
public String getFullHex(){
return(0x+ hex);
}
当我调用这个方法时,它给出了我的 NumberFormatException
java.lang.NumberFormatException:对于输入字符串:0xff0000
我无法理解发生了什么事。有人可以解释吗?
这会有帮助吗?
Integer.parseInt(00ff00,16)
16
表示您应该将字符串解释为16位(十六进制)。通过使用 2
可以解析二进制数, 8
代表八进制数。 10
是默认值并且解析十进制数字。
在您的情况下 Integer.parseInt(primary .getFullHex(),16)
由于 0x
前缀由 getFullHex()
- 摆脱,你会没事的。
So, In Java, you know how you can declare integers like this:
int hex = 0x00ff00;
I thought that you should be able to reverse that process. I have this code:
Integer.valueOf(primary.getFullHex());
where primary is an object of a custom Color class. It's constructor takes an Integer for opacity (0-99) and a hex String (e.g. 00ff00
).
This is the getFullHex
method:
public String getFullHex() {
return ("0x" + hex);
}
When I call this method it gives my this NumberFormatException
:
java.lang.NumberFormatException: For input string: "0xff0000"
I can't understand what's going on. Can someone please explain?
Will this help?
Integer.parseInt("00ff00", 16)
16
means that you should interpret the string as 16-based (hexadecimal). By using 2
you can parse binary number, 8
stands for octal. 10
is default and parses decimal numbers.
In your case Integer.parseInt(primary.getFullHex(), 16)
won't work due to 0x
prefix prepended by getFullHex()
- get rid of and you'll be fine.
这篇关于将十六进制字符串解析为Integer会抛出NumberFormatException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!