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`

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

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料