Converting negative numbers

五迷三道 提交于 2021-01-29 09:50:38

问题


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?


回答1:


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`



来源:https://stackoverflow.com/questions/56714851/converting-negative-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!