简体   繁体   中英

Shifting an integer to get an ARGB gray

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM