duanba5777 2017-06-15 05:49
浏览 37
已采纳

执行:字节。重复检查是否溢出

In Go's bytes package line 412 of bytes.go, there is a condition that goes as follows: (https://golang.org/src/bytes/bytes.go?s=10462:10501#L412)

len(b)*count/count != len(b)

This should apparently check for overflow but I don't understand how. Is this checking for some overflow of the underlying data type for integer? Or is this an error in implementation? len(b)*count/count should always be len(b)...no?

  • 写回答

1条回答 默认 最新

  • dopr25398 2017-06-15 06:13
    关注

    It's checking for overflow.

    // bytes.Repeat(make([]byte, 255), int((^uint(0))/255+1)) panics with the test.
    // Without the test, it returns a bad result.
    
    b := make([]byte, 255)
    count := int((^uint(0))/255 + 1)
    
    fmt.Println("count:", count)    // prints 16843010 on the playground
    fmt.Println("len(b):", len(b))  // prints 255
    fmt.Println("count * len(b): ", count*len(b))  // prints 254 
    fmt.Println("len(b) * count / count != len(b):", len(b)*count/count != len(b)) // prints false
    

    https://play.golang.org/p/3OQ0vB0WC4

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

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像