How does Java handle alpha channel?

Viewed 161

My understanding is that an RGB value with alpha value example could be this 0xffhexcode.

However, what I cannot understand is how 0xff0000ff, a solid blue with max alpha value, is an integer value greater than Integer.MAX_VALUE. How does the underline encoding in Java allow this to happen?

3 Answers

Actually the range for pixel is double the max value of Integer, because integer is signed and pixels are unsigned integer. So some colors have negative integer value. eg. white = -1

int and Integer is signed, the hexadecimal notation you used is unsigned.

EG try something like this:

System.out.printf( "%x%n",  -1 );

Will output:

ffffffff

This is an interesting question which boils down to the definition of integer literals. For a full reference see the language specs at https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.10.1

The crux of the matter is that for an integer literal expressed in decimals, you can only represent positive integers. With a hex literal you can express positive and negative values. And specifically the value will be negative if the first bit is on.

To quote the language specs:

A decimal numeral is either the single ASCII digit 0, representing the integer zero, or consists of an ASCII digit from 1 to 9 optionally followed by one or more ASCII digits from 0 to 9 interspersed with underscores, representing a positive integer.

A hexadecimal numeral consists of the leading ASCII characters 0x or 0X followed by one or more ASCII hexadecimal digits interspersed with underscores, and can represent a positive, zero, or negative integer.

So to be precise 0xffffffff is not actually greater than Integer.MAX_VALUE because it is negative (due to the leading bit being on). Too add to the things that don't look right at first glance you can try:

    System.out.println(Integer.MAX_VALUE == 0x7fffffff);
    System.out.println(Integer.MIN_VALUE == 0x80000000);

Which will output true for both lines.

Related