Color operation in go


There’re some simple color operations, but the output is wrong. I’m just wondering what happened here.


package main

import (

func main() {
    startColor := color.RGBA{0x34, 0xeb, 0x64, 0xff}
    endColor := color.RGBA{0x34, 0xc9, 0xeb, 0xff}
    fmt.Printf("%d-%d=%d\n", endColor.G, startColor.G, endColor.G-startColor.G)




color.RGBA.G is a uint8. Since 235 is bigger than 201, but uint8 doesn’t store negative numbers like -34, the value is instead wrapping.

There’s nothing color specific about the situation.
You get the same answer (222) with:

    var g1, g2 uint8 = 0xc9, 0xeb
    fmt.Println(g1 - g2)

So nothing unusual, just standard Go unsigned integer overflow wrapping. It isn’t even undefined behavior.

Answered By – Daniel Farrell

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.