故意的int溢出 [英] On-purpose int overflow
问题描述
我正在使用哈希函数murmur2
,该函数会向我返回uint64
.
I'm using the hash function murmur2
which returns me an uint64
.
然后我想将其存储在仅支持BIGINT
(带符号的64位)的PostgreSQL中.
I want then to store it in PostgreSQL, which only support BIGINT
(signed 64 bits).
因为我对数字本身不感兴趣,但对二进制值不感兴趣(因为我将其用作检测唯一性的ID(我的一组值约为1000个值,所以64位哈希对我来说足够了))希望通过只是"更改类型将其转换为int64
.
As I'm not interested in the number itself, but just the binary value (as I use it as an id for detecting uniqueness (my set of values being of ~1000 values, a 64bit hash is enough for me) I would like to convert it into int64
by "just" changing the type.
如何以一种使编译器满意的方式进行操作?
How does one do that in a way that pleases the compiler?
推荐答案
您可以简单地使用 conversion :
i := uint64(0xffffffffffffffff)
i2 := int64(i)
fmt.Println(i, i2)
输出:
18446744073709551615 -1
将uint64
转换为int64
始终会成功:它不会仅更改类型的内存表示.如果您尝试将无类型的整数常量值转换为int64
:
Converting uint64
to int64
always succeeds: it doesn't change the memory representation just the type. What may confuse you is if you try to convert an untyped integer constant value to int64
:
i3 := int64(0xffffffffffffffff) // Compile time error!
这是一个编译时错误,因为常量0xffffffffffffffff
(以任意精度表示)不适合int64
,因为适合int64
的最大值是0x7fffffffffffffff
:
This is a compile time error as the constant value 0xffffffffffffffff
(which is represented with arbitrary precision) does not fit into int64
because the max value that fits into int64
is 0x7fffffffffffffff
:
constant 18446744073709551615 overflows int64
这篇关于故意的int溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!