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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?