当将负数转换为无符号整数并稍后添加该值时,它会导致减去。
a := (uint8)(10)
b := (int8)(-8)
fmt.Println(a + (uint8)(b)) // result: 2
这是一种惯用的方法还是应该更明确地完成?
最佳答案
由于类型是无符号的,所以它是一个 overflow :
uint8(b)
是 248
,所以 a + uint8(b)
是 10+248=258=> 255 0 1 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.
同时使用 int8
:
a := int8(10)
b := int8(-8)
fmt.Println(a + b) // 2
fmt.Println(a - b) // 18
您可以避免溢出,例如 this :
a := uint8(10)
b := int8(-8)
c := uint8(b)
d := uint16(a) + uint16(c)
fmt.Println(d) // 258
你应该删除这里多余的括号:
a := (uint8)(10)
b := (int8)(-8)
fmt.Println(a + (uint8)(b))
使用这个:
a := uint8(10)
b := int8(-8)
fmt.Println(a + uint8(b))
关于go - 转换负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56714851/