randomgoint64uint64

Convert uint64 to int64 without loss of information


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.


Solution

  • Seeing -1 would be consistent with a process running as 32bits.

    See for instance the Go1.1 release notes (which introduced uint64)

    x := ^uint32(0) // x is 0xffffffff
    i := int(x)     // i is -1 on 32-bit systems, 0xffffffff on 64-bit
    fmt.Println(i)
    

    Using fmt.Printf("%b\n", y) can help to see what is going on (see ANisus' answer)

    As it turned out, the OP wheaties confirms (in the comments) it was run initially in 32 bits (hence this answer), but then realize 18446744073709551615 is 0xffffffffffffffff (-1) anyway: see ANisusanswer;