简体   繁体   English

Integer.valueOf() 无效整数

[英]Integer.valueOf() invalid int

I am trying to create color values from r,g,b values adding the alpha byte to create a color int.我正在尝试从 r、g、b 值创建颜色值,并添加 alpha 字节以创建颜色 int。

But I am getting errors using :但是我在使用时遇到错误:

Integer.valueOf(colorStr,16); Integer.valueOf(colorStr,16);

colorStr is the string that I build, now the value that sends me error is "0XFF2f6b55" it sends me invalid int. colorStr是我构建的字符串,现在向我发送错误的值是"0XFF2f6b55"它向我发送了无效的整数。

Java's integer covers values from -2^31 to 2^31-1 (2147483647). Java 的整数涵盖从 -2^31 到 2^31-1 (2147483647) 的值。 Your value is (4281297749) in decimal which is too big for java's integer.您的值是 (4281297749) 十进制,这对于 java 的整数来说太大了。

Java's long covers a much higher range of -2^63 to 2^63-1. Java 的long涵盖了 -2^63 到 2^63-1 的更高范围。 Which includes your value, so a suggestion would be to use Long.valueOf(colorStr, 16) and switch to using longs.其中包括您的价值,因此建议使用Long.valueOf(colorStr, 16)并切换到使用 longs。 (A suggestion that comes into play when the values that you are working with are outside of the range of integer values). (当您使用的值超出整数值范围时,该建议会起作用)。

It seemed to me that you were aware, but in case you were not;在我看来,你知道,但万一你没有; the 0x should be removed if it is part of the string value, as it will give an invalid format exception if left in.如果0x是字符串值的一部分,则应将其删除,因为如果留在其中,它将给出无效格式异常。

Your string is too big for a signed int - they go from -0x80000000 to 0x7FFFFFFF .您的字符串对于带符号的 int 来说太大了 - 它们从-0x800000000x7FFFFFFF Try:尝试:

int i = (int) Long.parseLong(colorStr.substring(2), 16);

This will result in a negative int , which might not be what you want.这将导致负值int ,这可能不是您想要的。 (When working with colors, it's probably more convenient to work with a tuple of values for the red, green, blue, and alpha component.) (使用颜色时,使用红色、绿色、蓝色和 alpha 分量的值元组可能更方便。)

Neither valueOf() or parseInt() / parseLong() will recognize the 0x prefix, you need to get rid of it. valueOf()parseInt() / parseLong()都不会识别0x前缀,您需要摆脱它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM