Why Am I Getting a Negative Number from this code in processing?
The reason is describe here in Processing documentation:
From a technical standpoint, colors are 32 bits of information ordered as AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB where the A's contain the alpha value, the R's are the red value, G's are green, and B's are blue. Each component is 8 bits (a number between 0 and 255). These values can be manipulated with bit shifting.
The color
type is secretly an int
. In second reference bit shifting is descibed how you can use this value to extract alpha, red, green and blue:
// Using "right shift" as a faster technique than red(), green(), and blue()
color argb = color(204, 204, 51, 255);
int a = (argb >> 24) & 0xFF;
int r = (argb >> 16) & 0xFF; // Faster way of getting red(argb)
int g = (argb >> 8) & 0xFF; // Faster way of getting green(argb)
int b = argb & 0xFF; // Faster way of getting blue(argb)
fill(r, g, b, a);
rect(30, 20, 55, 55);
-
>>
- shift bits to right, i.e. cut last 24bits -
& 0xFF
- get only last 8 bits
and according to the authors, this is a faster method than red()
, green()
, and blue()
functions.
If you want to compute this value by yourself, I tried to recreate the calculation:
int a = 255;
int r = 204;
int g = 204;
int b = 51;
int res = ((-128*int(a/128)+int(a%128))<<24) | (r << 16) | (g << 8) | b;
-
((-128*int(a/128)+int(a%128))<<24)
- Alpha is between [0;255]. In their solution alpha is tranform between [-128;127] with overflow of range, i.e. 126=>126, 127=>127, 128=>-128, 129=>-127 and so on 255=>-1