Java 以整数形式存储十六进制值 (0x45E213)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9749482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:07:12  来源:igfitidea点击:

store hex value (0x45E213) in an integer

javaandroidhexnumberformatexception

提问by Dion Segijn

In my application I used a converter to create from 3 values > RGB-colors an Hex value. I use this to set my gradient background in my application during runtime.

在我的应用程序中,我使用转换器从 3 个值 > RGB 颜色创建一个十六进制值。我使用它在运行时在我的应用程序中设置我的渐变背景。

Now is this the following problem. The result of the converter is a (String)#45E213, and this can't be stored in an integer. But when you create an integer,

现在这是以下问题。转换器的结果是 a (String)#45E213,并且这不能存储在整数中。但是当你创建一个整数时,

int hex = 0x45E213;

it does work properly, and this doesn't give errors.

它确实可以正常工作,并且不会出错。

Now I knew of this, I Replaced the #to 0x, and tried it to convert from String to Integer.

现在我知道了这一点,我替换了#to 0x,并尝试将其从 String 转换为 Integer。

int hexToInt = new Integer("0x45E213").intValue();

But now I get the numberFormatException, because while converting, it will not agree with the character E?

但现在我明白了numberFormatException,因为在转换时,它不会与字符一致E

How can I solve this? Because I really need it as an Integer or Java/Eclipse won't use it in its method.

我该如何解决这个问题?因为我真的需要它作为整数或 Java/Eclipse 不会在其方法中使用它。

采纳答案by Matt Esch

http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html

http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html

The Integer constructor with a string behaves the same as parseInt with radix 10. You presumably want String.parseInt with radix 16.

带有字符串的 Integer 构造函数的行为与基数为 10 的 parseInt 相同。您可能想要基数为 16 的 String.parseInt。

Integer.parseInt("45E213", 16)

or to cut off the 0x

或切断 0x

Integer.parseInt("0x45E213".substring(2), 16);

or

或者

Integer.parseInt("0x45E213".replace("0x",""), 16);

回答by Some one Some where

This Method accepts your String you can use Color.parseColor(String)but you need to replace 0xprefix with #

此方法接受您可以使用的字符串,Color.parseColor(String)但您需要将0x前缀替换为#

回答by Adam

The lesser known Integer.decode(String) might be useful here. Note it will also do leading zeros as octal, which you might not want, but if you're after something cheap and cheerful...

鲜为人知的 Integer.decode(String) 在这里可能很有用。请注意,它也会将前导零作为八进制,你可能不想要,但如果你想要一些便宜和快乐的东西......

int withHash = Integer.decode("#45E213");
System.out.println(Integer.toHexString(withHash));

int withZeroX = Integer.decode("0x45E213");
System.out.println(Integer.toHexString(withZeroX));

Output

输出

45e213
45e213