对 RGB 值使用逻辑位移位
当谈到按位逻辑时,我有点天真,我有一个可能是一个简单的问题...基本上,如果我有这个(是 ActionScript,但可以应用于多种语言):
var color:uint = myObject.color;
var red:uint = color >>> 16;
var green:uint = color >>> 8 & 0xFF;
var blue:uint = color & 0xFF;
我想知道 `& 到底是什么? 0xFF'正在处理绿色和蓝色。我了解 AND 运算的作用,但为什么这里需要它(或者是一个好主意)?
此代码的来源在这里:http://alexgblog.com/?p=680
尖端。 亚历克斯
I'm a bit naive when it comes to bitwise logic and I have what is probably a simple question... basically if I have this (is ActionScript but can apply in many languages):
var color:uint = myObject.color;
var red:uint = color >>> 16;
var green:uint = color >>> 8 & 0xFF;
var blue:uint = color & 0xFF;
I was wondering what exactly the `& 0xFF' is doing to green and blue. I understand what an AND operation does, but why is it needed (or a good idea) here?
The source for this code was here: http://alexgblog.com/?p=680
Appreciate the tips.
Alex
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 RGB 中,红色有 8 位,绿色有 8 位,蓝色有 8 位。您将 3 个字节存储在一个 int 中,该 int 有 4 个字节,如下所示:
要将它们提取为单独的值,您需要右移正确的位数,以便将与要提取的颜色相对应的字节放入 int 的最低有效字节中,然后将 int 的其余部分放入 0 中,这样只让该字节值。最后一部分是通过使用掩码 0xFF 的 AND 运算来完成的。 AND 留下了 int 中应用相同值的唯一字节,将其余字节保留为 0。
发生的情况如下:
您的颜色变量如下所示: 0x00RRGGBB
右移 16 位颜色结果为: 0x000000RR,从而得到红色值。
但是对于:
右移颜色 8 位后,它留下这个结果 0x0000RRGG,但这里我们只需要留下 GG 位,因此我们使用掩码 0xFF 进行 AND 运算,或者更清楚的是 0x000000FF,如您所知,AND 留下旧的掩码为 1 的位值和掩码为 0 的位为零,因此执行
0x0000RRGG & 的结果是0x000000FF = 0x000000GG
这是绿色的值。同样的方法也适用于提取蓝色值。In RGB you have 8 bits for Red, 8 bits for Green and 8 bits for Blue. You are storing the 3 bytes in an int, which has 4 bytes in this way:
To extract them to separate values you need to right shift the correct number of bits in order to put the byte corresponding to the color you want to extract in the least significant byte of the int, and then put the rest of the int in 0 so as to let that byte value only. The last part is done by using the AND operation with mask 0xFF. The AND leaves the only byte of the int where it is applied with the same value, leaving the rest bytes in 0.
This is what happens:
You have the color variable like this: 0x00RRGGBB
Right-shifting 16 bits color results in: 0x000000RR, resulting in the red value.
But for:
After right-shifting color 8 bits it leaves this result 0x0000RRGG, but here we only need the GG bits left so we apply the AND operation with the mask 0xFF or to be more clear 0x000000FF, as you show know AND leaves the old bits values where the mask is 1 and zeros there the mask is 0, so the result of doing
0x0000RRGG & 0x000000FF = 0x000000GG
which is the value for green. The same is applied to extract the blue value.