Home > other >  Color operation in go
Color operation in go

Time:03-13

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

main.c:

package main

import (
    "fmt"
    "image/color"
)

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)
}

output:

201-235=222

CodePudding user response:

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.

  • Related