gpt4 book ai didi

go - golang RGBA.RGBA() 方法为什么使用 |和 <
转载 作者:IT老高 更新时间:2023-10-28 13:10:01 24 4
gpt4 key购买 nike

在 golang 颜色包中,有一种方法可以从 RGBA 中获取 r,g,b,a 值对象:

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
}

如果我要实现这个简单的功能,我会写这个

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
}

是什么原因r |= r << 8用过吗?

最佳答案

来自优秀的“The Go image package”博文:

[...] 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.

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]

因此,如果我们查看值为 c.R = 10101010 的颜色的位表示,那么这个操作

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

有效地将第一个字节复制到第二个字节。

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

这相当于乘以因子 0x101,并将所有 256 个可能的值均匀分布在 [0, 65535] 范围内。

关于go - golang RGBA.RGBA() 方法为什么使用 |和 <<?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35374300/

24 4 0

Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com