gpt4 book ai didi

在命令行和 Playground 上进行整数溢出设置

转载 作者:IT王子 更新时间:2023-10-29 01:27:17 24 4
gpt4 key购买 nike

这个程序在我的机器上运行良好(go1.2.1 linux/amd64):

package main

import "fmt"

const bigint = 1<<62

func main() {
fmt.Println(bigint)
}

但是对于 go playground,它给出了溢出错误 - http://play.golang.org/p/lAUwLwOIVR

看来我的构建配置了 64 位整数常量,playground 配置了 32 位。

但是spec say该实现必须为常量提供至少 256 位的精度?

另请参阅 my other question 中的代码-- 扫描器标准包有代码:

const GoWhitespace = 1<<'\t' | 1<<'\n' | 1<<'\r' | 1<<' '

由于空间是 32,这在 32 位 Playground 上根本不起作用。

这怎么可能?

最佳答案

一般常量

常量本身不受精度限制,但在代码中使用时,它们会转换为合适的类型。来自spec :

A constant may be given a type explicitly by a constant declaration or conversion, or implicitly when used in a variable declaration or an assignment or as an operand in an expression. It is an error if the constant value cannot be represented as a value of the respective type. For instance, 3.0 can be given any integer or any floating-point type, while 2147483648.0 (equal to 1<<31) can be given the types float32, float64, or uint32 but not int32 or string.

如果你有

const a = 1 << 33
fmt.Println(a)

你会get an overflow error作为整数常量的默认类型 int无法保存值 1 << 3332 bit environments .如果将常量转换为 int64在所有平台上一切都很好:

const a = 1 << 33
fmt.Println(int64(a))

扫描器

常量 GoWhitespace不直接用于扫描仪。Whitespace attribute用于 Scanner类型是 uint64 类型和 GoWhitespace is assigned to it :

s.Whitespace = GoWhitespace

这意味着你处理一个 uint64值(value)和1 << ' ' (又名 1 << 32 )完全有效。

示例(on play):

const w = 1<<'\t' | 1<<'\n' | 1<<'\r' | 1<<' '

c := ' '

// fmt.Println(w & (1 << uint(c))) // fails with overflow error
fmt.Println(uint64(w) & (1 << uint(c))) // works as expected

关于在命令行和 Playground 上进行整数溢出设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22439698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com