Since the type is unsigned it is an overflow:
uint8(b)
is 248
, so a + uint8(b)
is 10+248=258=256+2 => 2
my question is more about how to subtract from unsigned integers when
the value (sometimes you want to add and sometimes subtract) is coming
from an argument (that must be a signed type) which makes it so that
you have to do type conversion before subtracting/adding.
You may using both int8
:
a := int8(10)
b := int8(-8)
fmt.Println(a + b) // 2
fmt.Println(a - b) // 18
You may avoid the overflow, like this:
a := uint8(10)
b := int8(-8)
c := uint8(b)
d := uint16(a) + uint16(c)
fmt.Println(d) // 258
You should remove 3-pair of superfluous Parentheses here:
a := (uint8)(10)
b := (int8)(-8)
fmt.Println(a + (uint8)(b))
Use this:
a := uint8(10)
b := int8(-8)
fmt.Println(a + uint8(b))
See:
confusion about convert `uint8` to `int8`