1
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.

Community
  • 1
  • 1
L. Swifter
  • 3,179
  • 28
  • 52

1 Answers1

4

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?

Community
  • 1
  • 1
slipperyseal
  • 2,728
  • 1
  • 13
  • 15
  • thanks, after reading your answer, I know why the android studio give me the warning. But I just do some bit operations, so I think there is no need to do special things for the high bit (sign bit). IDE gives me a warning but this code can work OK, am I right ? – L. Swifter Apr 11 '17 at 05:50
  • for the colour operations, all that matters is the bits. the cast i have explained preserves the bits. its just convincing the compiler everything is ok. for example 0xFFFFFFFF is actually -1 as a signed value, and 0xFFFFFFFF as unsigned. But that's still 32 bits of 1. Its just a work around because Java has no unsigned values. – slipperyseal Apr 11 '17 at 05:55