dongxing8650 2019-06-22 10:51
浏览 113
已采纳

转换负数

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条回答 默认 最新

  • doumaojin4008 2019-06-22 12:00
    关注

    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`

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件