32位系统上的整数溢出

huangapple go评论69阅读模式
英文:

Int overflow on 32-bit systems

问题

这是我的测试函数。

if -1 != cmp(2<<32, keys[2].Distance(keys[5])) {
    t.Errorf("2<<32 should be smaller")
}

它导致以下错误:

常量 8589934592 溢出 int

在32位系统上是否有可能使其工作?

编辑:这是用于比较键的 Distance 函数。

// Distance 返回此键空间中的距离度量
func (s *xorKeySpace) Distance(k1, k2 Key) *big.Int {
    // 对键进行异或运算
    k3 := XOR(k1.Bytes, k2.Bytes)

    // 将其解释为整数
    dist := big.NewInt(0).SetBytes(k3)
    return dist
}
英文:

This is my test function.

if -1 != cmp(2&lt;&lt;32, keys[2].Distance(keys[5])) {
		t.Errorf(&quot;2&lt;&lt;32 should be smaller&quot;)
	}

it results in the folllowing error

> constant 8589934592 overflows int

Is it possible to make this work on a 32 bit system?

edit: also this is the Distance function for comparing keys

// Distance returns the distance metric in this key space
func (s *xorKeySpace) Distance(k1, k2 Key) *big.Int {
	// XOR the keys
	k3 := XOR(k1.Bytes, k2.Bytes)

	// interpret it as an integer
	dist := big.NewInt(0).SetBytes(k3)
	return dist
}

答案1

得分: 1

确保你使用的是64位整数,最好的方法是使用uint64来确保大小。

type Key int64 // 或者 uint64

假设key被定义为int,否则只需将所有函数签名从int更改为int64

英文:

Make sure you work on an 64bit int, the best way is to ensure the size by using uint64

type Key int64 // or uint64

Assuming key is defined to be int, otherwise just change all your function signatures from int to int64.

huangapple
  • 本文由 发表于 2014年10月4日 03:49:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/26185795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定