Golang:专用int溢出 [英] Golang: on-purpose int overflow

查看:6198
本文介绍了Golang:专用int溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用哈希函数 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).

由于我对数字本身不感兴趣,但只是二进制值(因为我将它用作检测唯一性的标识符(我的值集为〜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

You can simply use a type conversion:

i := uint64(0xffffffffffffffff)
i2 := int64(i)
fmt.Println(i, i2)

输出:

Output:

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

这篇关于Golang:专用int溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆