dongshi6844 2019-01-13 17:33
浏览 453
已采纳

如何计算golang溢出?

I am a newbie to Golang

package main

import "fmt"

func main() {
    var u uint8 = 255
    var m uint16 = 255
    fmt.Println(u, u-1, u*(u-1))
    fmt.Println(m, m+1, m*m)
}

OUTPUT

./g2
255 254 2
255 256 65025

I understand that I have overflow in the first case. But why did I get 2 as a result?

  • 写回答

1条回答 默认 最新

  • du2986 2019-01-13 17:57
    关注

    You’ve already hinted at overflow, and in fact this is exactly what’s happening here. You already know what u and u-1 are (255 and 254 respectively), so let’s multiply those together. This gives us 64770, or in binary:

    64770       = 1111 1101 0000 0010
    

    This result is 16 bits wide, but we’re storing it in a uint8 which is only 8 bits wide. It is therefore truncated to the 8 least significant bits. Mathematically, this is equivalent to performing 64770 mod 2^8 or 64770 mod 256. Programatically, it’s equivalent to performing 64770 & (1 << 7) or 64770 & 256:

    64770       = 1111 1101 0000 0010
    256         =           1111 1111
    64770 & 256 = 0000 0000 0000 0010 = 2
    

    However you chose to imagine this operation, the result is 2.

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

报告相同问题?

悬赏问题

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