duanlu1279 2016-02-13 00:02
浏览 155
已采纳

为什么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].

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制