Java Color(int rgba) 构造函数和 int 溢出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18245175/
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
Java Color(int rgba) constructor and int overflow
提问by ZachB
According to the docs, this constructor exists:
根据文档,此构造函数存在:
public Color(int rgba,
boolean hasalpha)
I'm failing to see how you could use this to create the equivalent of Color(255,255,255,255)
(e.g. 0xFFFFFFFF
) given that java has no unsigned ints, however.
但是,鉴于 java 没有无符号整数,我看不出您如何使用它来创建Color(255,255,255,255)
(eg 0xFFFFFFFF
)的等价物。
How do you use this constructor for a "big" color?
你如何将这个构造函数用于“大”颜色?
EDIT
编辑
Evidently the constructor can be used (surprise), but parsing an RGBa color string like this fails:
显然可以使用构造函数(惊喜),但是解析这样的 RGBa 颜色字符串失败:
int x = Integer.parseInt("0xFFFFFFFF", 16); // Number format error
Color c = new Color(x, true);
The solution seems to be to use BigInteger to do the parsing. Sorry for the misdirected question!
解决方案似乎是使用 BigInteger 进行解析。抱歉问错了问题!
采纳答案by devsnd
Your question is not misdirected, but you seems to have misunderstood Kon's answer:
你的问题没有误导,但你似乎误解了 Kon 的回答:
You are right about Java's Integer being signed all the time, but this doesn't mean that there are less bits of information in that number.
您一直对 Java 的 Integer 进行签名是对的,但这并不意味着该数字中的信息位较少。
When you create a Color:
创建颜色时:
new Color(255, 255, 255, 255)
it is the same as using:
它与使用相同:
new Color(0xFFFFFFFF, true)
or using:
或使用:
new Color(0b11111111111111111111111111111111, true)
0xFFFFFFFF
is in fact -1
, but this doesn't mean that any of the bits change; It's only a question of representation. The Color
just cuts out the necessary bits for each color component.
0xFFFFFFFF
实际上是-1
,但这并不意味着任何位都发生了变化;这只是一个代表问题。在Color
刚刚削减了必要位为每种颜色分量。
So you can, in fact, create your desired color using:
因此,实际上,您可以使用以下方法创建所需的颜色:
Color c = new Color(-1,true);
System.out.println(c);
System.out.println(c.getAlpha());
which yields:
产生:
java.awt.Color[r=255,g=255,b=255]
255
回答by Kon
Go binary.
去二进制。
Color c = new Color(0b11111111111111111111111111111111, true);
颜色 c = 新颜色(0b111111111111111111111111111111111, true);
As per the Java docs, "alpha component is in bits 24-31, the red component is in bits 16-23, the green component is in bits 8-15, and the blue component is in bits 0-7"
根据 Java 文档,“alpha 分量在第 24-31 位,红色分量在第 16-23 位,绿色分量在第 8-15 位,蓝色分量在第 0-7 位”