1

Java API has this constructor:

public Color(int rgba, boolean hasalpha)

I call it like this:

g.setColor(new Color(0xFF1874CD, true));

The Max integer value is 0x7FFFFFFF. Why the above 0xFF1874CD doesn't cause overflow?

peterboston
  • 877
  • 1
  • 12
  • 24

2 Answers2

2
0xFF1874CD

is

  F    F    1    8    7    4    C    D
1111 1111 0001 1000 0111 0100 1100 1101

which, in decimal, is

-15174451

That number can be represented as an int.

The Java Language Specification states

The largest positive hexadecimal, octal, and binary literals of type int - each of which represents the decimal value 2147483647 (231-1) - are respectively:

0x7fff_ffff,
[...]

The most negative hexadecimal, octal, and binary literals of type int - each of which represents the decimal value -2147483648 (-231) - are respectively:

0x8000_0000,
[...]
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

In Java, any int value greater than 0x7FFFFFFF and equal to or less than 0xFFFFFFFF will be a treated as a negative number if printed directly.

However, this does not cause problems when dealing with colors as the |, &, and >> operators can be used to find the red, green, blue, and alpha channels just fine, as though the number were positive still.

In most cases, only negation, subtraction, and rendering the number as text will care about whether the number is negative or not. In other cases, there's essentially no difference between a negative number and a very large positive number.

See this Wikipedia article about Two's Complement for more details about how this all works.

Charles Spencer
  • 626
  • 1
  • 6
  • 17