这段代码有什么不对,数字溢出警告(what's wrong this this code, Numeric overflow warning)

编程入门 行业动态 更新时间:2024-10-25 16:26:20
这段代码有什么不对,数字溢出警告(what's wrong this this code, Numeric overflow warning) fillColor = (fillColor & (0xFF << 24)) | (colorRGB & 0xFFFFFF);

以上是我的代码,我认为这应该没问题。 但Android Studio给了我一个警告:

表达式中的数字溢出少...(Ctrl + F1)

该检查检查在计算期间溢出的表达式,即:a = 1.0 / 0.0;

我找不到代码有什么问题,请帮忙。

fillColor = (fillColor & (0xFF << 24)) | (colorRGB & 0xFFFFFF);

Above is my code, and I think this should be OK. But the Android Studio give me a warning saying :

Numeric overflow in expression less... (Ctrl+F1)

This inspection checks for expressions which overflow during computation, i.e.:       a = 1.0/0.0;

I can not find what is the matter with the code, please help.

最满意答案

0xFF << 24等于0xFF000000 ,“技术上”不适合作为有符号值的int(例如,改变<< 24到23并看到错误消失)。

这个“hack”将值设置为long,但然后将其转换为int。 相同的位最终会出现在值中,但是演员特别告诉编译器您很乐意以这种方式截断该值。

(int)((long)0xFF << 24);

所以为了特别修复你的代码,我将0xFF << 24扩展为long(注意尾随L),然后将其转换为int。

fillColor = (fillColor & (int)0xFF000000L) | (colorRGB & 0xFFFFFF);

另请参见为什么Java能够将0xff000000存储为int?

0xFF << 24 equals 0xFF000000 which "technically" doesn't fit into an int as a signed value (eg. change << 24 to 23 and see the error go away).

This "hack" sets up the value as a long, but then casts it to an int. The same bits end up in the value but the cast specifically tells the compiler you're happy to truncate the value in this way.

(int)((long)0xFF << 24);

So to fix your code in particular, i have expanded 0xFF << 24 as a long (note the trailing L) and then cast it to an int.

fillColor = (fillColor & (int)0xFF000000L) | (colorRGB & 0xFFFFFF);

See also Why is Java able to store 0xff000000 as an int?

更多推荐

本文发布于:2023-08-03 08:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1384964.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么   这段   代码   数字   wrong

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!