Golang: end-to-end int overflow

I use the hash function murmur2 , which returns me uint64 .

Then I want to save it in PostgreSQL, which only supports BIGINT (signed 64 bits).

Since I am not interested in the number itself, itโ€™s just a binary value (since I use it as an identifier for uniqueness (my set of values โ€‹โ€‹is ~ 1000 values, a 64-bit hash is enough for me) I would like to convert it to int64 by "just" changing type.

How to do it the way the compiler likes it?

+3
source share
1 answer

You can simply use conversion type:

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

Output:

 18446744073709551615 -1 

Converting uint64 to int64 always succeeds: it does not change the memory representation of only the type. Which may confuse you if you try to convert the value of an untyped integer value to int64 :

 i3 := int64(0xffffffffffffffff) // Compile time error! 

This is a compile-time error, since the constant value 0xffffffffffffffff (which is represented with arbitrary precision) does not fit into int64 , because the maximum value that fits into int64 is 0x7fffffffffffffff :

 constant 18446744073709551615 overflows int64 
+7
source

Source: https://habr.com/ru/post/1264065/


All Articles