转换负数 [英] Converting negative numbers
问题描述
将负数转换为无符号整数,然后再加上该值将导致相减.
When converting a negative number to an unsigned integer and later adding that value it results in subtracting.
a := (uint8)(10)
b := (int8)(-8)
fmt.Println(a + (uint8)(b)) // result: 2
这是惯用的方法还是应该更明确地进行?
Is this an idiomatic approach or should it be done more explicitly?
推荐答案
由于类型是未签名的,因此它是 溢出 : uint8(b)
是 248
,所以 a + uint8(b)
是 10 + 248 = 258 = 256 + 2 =>2
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.
您可以同时使用 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
您应在此处删除3对多余的括号:
You should remove 3-pair of superfluous Parentheses here:
a:=(uint8)(10)
b:=(int8)(-8)
fmt.Println(a +(uint8)(b))
a := (uint8)(10)
b := (int8)(-8)
fmt.Println(a + (uint8)(b))
使用此:
a := uint8(10)
b := int8(-8)
fmt.Println(a + uint8(b))
这篇关于转换负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!