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 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗