Reputation: 67
Let's say i have:
int x = 140;
And i want to get the result of:
int y = new Color(x, x, x).getRGB()
From Java API documentation:
getRGB()
Gets the RGB value representing the color in the default RGB ColorModel.
(bits 24-31 are 0xff, 16-23 are red, 8-15 are green, 0-7 are blue)
But i'm not sure about how shifting works, is this right?
int y = 0xff + x<<16 + x<<8 + x;
Upvotes: 0
Views: 386
Reputation: 93872
Your approach would work if you don't forgot to shift correctly the alpha value.
int y = (0xff<<24) + (x<<16) + (x<<8) + x;
However a common approach is to directly shift the bits (with a combination of left shift and bitwise or). I presume because it's faster to apply the bitwise than the addition and it's enough readable to manipulate ARGB values for a human.
int y = (0xff<<24) | (x<<16) | (x<<8) | x;
You can view it like this.
(0xff << 24) => 0xff000000
| (x<<16) => 0xff8c0000
| (x<<8) => 0xff8c8c00
| x => 0xff8c8c8c
Upvotes: 1