Why is 2^63 negative?

In Julia, 2 is an integer literal with 64 bits length. 2^63 overflows into the most signifant bit and thus is negative:

julia> bitstring(2)
"0000000000000000000000000000000000000000000000000000000000000010"

julia> bitstring(2^32)
"0000000000000000000000000000000100000000000000000000000000000000"

julia> bitstring(2^63)
"1000000000000000000000000000000000000000000000000000000000000000"

Since julia is using machine integers (which use Twos-Complement), an integer with a leading 1 is negative.

In contrast, python automatically grows the integer type as necessary - this is much slower for general use though, which is why its not done in julia.

8 Likes