drkbpwk609294 2014-03-16 22:32
浏览 186
已采纳

无符号整数溢出

Go spec say on unsigned integer overflow:

For unsigned integer values, the operations +, -, *, and << are computed modulo 2n, where n is the bit width of the unsigned integer's type. Loosely speaking, these unsigned integer operations discard high bits upon overflow, and programs may rely on ''wrap around''.

I try to test it, but get inconsistent result - http://play.golang.org/p/sJxtSHbigT:

package main

import "fmt"

func main() {
    fmt.Println("test")
    var num uint32 = 1 << 35
}

This give error:

prog.go:7: constant 34359738368 overflows uint32
 [process exited with non-zero status]

But according to spec should be no error but rather I should seen 0.

  • 写回答

2条回答 默认 最新

  • duanpei4455 2014-03-16 22:36
    关注

    The specification you quote refers specifically to the results of "the operations +, -, *, and <<". You're trying to define a constant, not looking at the result of one of those operations.

    You also can't use those over-sized values for the input of those operations. The compiler won't wrap any values for you; that's just the runtime behaviour of those operations.

    package main
    
    import "fmt"
    
    func main() {
        var num uint32 = 1 + 1 << 35
        fmt.Printf("num = %v
    ", num)
    }
    
    prog.go:6: constant 34359738369 overflows uint32
     [process exited with non-zero status]
    

    Here's an interesting example.

    var num uint32 = (1 << 31) + (1 << 31)
    fmt.Printf("num = %v
    ", num)
    
    prog.go:6: constant 4294967296 overflows uint32
     [process exited with non-zero status]
    

    In this case, the compiler attempts to evaluate (1 << 31) + (1 << 31) at compile-time, producing the constant value 4294967296, which is too large to fit.

    var num uint32 = (1 << 31)
    num += (1 << 31)
    fmt.Printf("num = %v
    ", num)
    
    num = 0
    

    In this case, the addition is performed at run-time, and the value wraps around as you'd expect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作