简体   繁体   English

移位整数以获得ARGB灰色

[英]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: 从Java API文档中:

getRGB() 的getRGB()
Gets the RGB value representing the color in the default RGB ColorModel. 获取表示默认RGB ColorModel中颜色的RGB值。
(bits 24-31 are 0xff, 16-23 are red, 8-15 are green, 0-7 are blue) (位24-31是0xff,16-23是红色,8-15是绿色,0-7是蓝色)

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. 如果您不忘记正确移动Alpha值,则您的方法将行得通。

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. 我猜想是因为按位应用比加法更快,并且可读性足以为人类操作ARGB值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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