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 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用
  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题