duanlu1279 2016-02-13 00:02

# 为什么golang RGBA.RGBA（）方法使用| 和<<？

In the golang color package, there is a method to get r,g,b,a values from an `RGBA` object:

``````func (c RGBA) RGBA() (r, g, b, a uint32) {
r = uint32(c.R)
r |= r << 8
g = uint32(c.G)
g |= g << 8
b = uint32(c.B)
b |= b << 8
a = uint32(c.A)
a |= a << 8
return
}
``````

If I were to implement this simple function, I would just write this

``````func (c RGBA) RGBA() (r, g, b, a uint32) {
r = uint32(c.R)
g = uint32(c.G)
b = uint32(c.B)
a = uint32(c.A)
return
}
``````

What's the reason `r |= r << 8` is used?

• 写回答

#### 4条回答默认 最新

• dongyu2300 2016-02-13 00:28
关注

From the the excellent "The Go image package" blogpost:

[...] the channels have a 16-bit effective range: 100% red is represented by RGBA returning an r of 65535, not 255, so that converting from CMYK or YCbCr is not as lossy. Third, the type returned is uint32, even though the maximum value is 65535, to guarantee that multiplying two values together won't overflow.

and

Note that the R field of an RGBA is an 8-bit alpha-premultiplied color in the range [0, 255]. RGBA satisfies the Color interface by multiplying that value by 0x101 to generate a 16-bit alpha-premultiplied color in the range [0, 65535]

So if we look at the bit representation of a color with the value `c.R = 10101010` then this operation

``````r = uint32(c.R)
r |= r << 8
``````

effectively copies the first byte to the second byte.

``````   00000000000000000000000010101010 (r)
| 00000000000000001010101000000000 (r << 8)
--------------------------------------
00000000000000001010101010101010 (r |= r << 8)
``````

This is equivalent to a multiplication with the factor `0x101` and distributes all 256 possible values evenly across the range [0, 65535].

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 python使用pulp线性优化时报错
• ¥15 开源或低价数据中台哪个最好
• ¥15 arduino编程出现字符串疑似覆盖现象
• ¥15 我的b站在没有碰到屏幕的情况下偶尔会自动跳出进度条，就像在屏幕上点了一下一样，但我并没有点。而且视频进度并没有变。这可能是什么原因造成的？
• ¥30 STK matlab python仿真
• ¥15 关于IMageEnView 图标定位问题
• ¥20 求解答（matlab）
• ¥30 ffmpeg库使用过程中遇到的问题
• ¥15 pyqt5 中python如何通过Qtwebchannel主动发消息给web前端
• ¥15 关于HTML中title获取xml内容的问题