Go: convert uint64 to int64 without loss of information

wheaties picture wheaties · Nov 13, 2014 · Viewed 8.7k times · Source

The problem with the following code:

var x uint64 = 18446744073709551615
var y int64 = int64(x)

is that y is -1. Without loss of information, is the only way to convert between these two number types to use an encoder and decoder?

buff bytes.Buffer
Encoder(buff).encode(x)
Decoder(buff).decode(y)

Note, I am not attempting a straight numeric conversion in your typical case. I am more concerned with maintaining the statistical properties of a random number generator.

Answer

ANisus picture ANisus · Nov 13, 2014

Your conversion does not lose any information in the conversion. All the bits will be untouched. It is just that:

uint64(18446744073709551615) = 0xFFFFFFFFFFFFFFFF
int64(-1)                    = 0xFFFFFFFFFFFFFFFF

Try:

var x uint64 = 18446744073709551615 - 3

and you will have y = -4.


For instance: playground

var x uint64 = 18446744073709551615 - 3
var y int64 = int64(x)
fmt.Printf("%b\n", x)
fmt.Printf("%b or %d\n", y, y)

Output:

1111111111111111111111111111111111111111111111111111111111111100
-100 or -4