为什么golang RGBA.RGBA()方法使用|和<<?

前端之家收集整理的这篇文章主要介绍了为什么golang RGBA.RGBA()方法使用|和<<?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在golang颜色包中,有一个方法可以从RGBA对象获取r,g,b的值:
func (c RGBA) RGBA() (r,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,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的乘法,并在范围[0,65535]中均匀分布所有256个可能的值.

原文链接:https://www.f2er.com/go/186800.html

猜你在找的Go相关文章