cogmission cogmission - 3 months ago 10
Java Question

Get same left shift value in Java as Python

Specifically I want to take this number:

x = 1452610545672622396

and perform

x ^= (x << 21) // In Python I do x ^= (x << 21) & 0xffffffffffffffff

and get: 12043412836254060860 // Which is what I get in Python

instead of: -6403331237455490756 // Which is what I get in Java (and don't want)

Answer

You can store x as a BigInteger and call shiftLeft on it, then do your xor operation.

Why: You need 61 bits to represent 1452610545672622396, and shifting it left 21 will overflow a long (64 bits).

--

You cannot convert the result back to a long, because it needs 64 bits and you can only use 63 of those + sign. (log2 12043412836254060860 = 63.3848780807)

Here's sample code:

public static void main(String[] args) {
    long x = 1452610545672622396L;

    BigInteger bigX = BigInteger.valueOf(x);
    bigX = bigX.shiftLeft(21).xor(bigX).and(new BigInteger("ffffffffffffffff", 16));

    System.out.println(bigX); // 12043412836254060860
    System.out.println(bigX.longValue()); // -6403331237455490756
}