Converting uint64 to int64 for Hash Function Output
When working with hash functions that return uint64 values, such as murmur2, and storing the result in a database like PostgreSQL that supports only BIGINT (int64), it's necessary to convert the uint64 to an int64.
Solution: Type Conversion
The simplest solution is to use a type conversion:
i := uint64(0xffffffffffffffff) i2 := int64(i)
This conversion succeeds as it doesn't change the memory representation, only the type. The resulting int64 value will have the same binary representation as the original uint64.
Output:
18446744073709551615 -1
Additional Note:
Converting an untyped integer constant value directly to int64 can result in a compile time error, as the constant value may not fit into int64's range. For example:
i3 := int64(0xffffffffffffffff) // Compile time error!
This is because the constant value 0xffffffffffffffff has arbitrary precision and exceeds the maximum value of int64, which is 0x7fffffffffffffff.
The above is the detailed content of How to Safely Convert a uint64 Hash Output to an int64 for Database Storage?. For more information, please follow other related articles on the PHP Chinese website!