How do bit operations on Long work in Java?

I have the following code:

@Test
public void simpleTest() {
    long x = 0;
    x |= 3L;
    System.out.println(showBits(x));
}

private String showBits(long x) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < 64; i++) {
        builder.append((x & (1 << i)) > 0 ? "1" : "0");
    }
    return builder.reverse().toString();
}

As a result, I expected to see this sequence:, 00...011but in fact it turned out:

0000000000000000000000000000001100000000000000000000000000000011

I understand that it is int32 bits, and long64. It is not clear to me why the longtype is updated by the operator or every 32 bits, not just the first ones.

If you deduce through System.out.println(x), it will be 3. And why is the triple in the bit representation duplicated?

It seems that the error is somewhere in the loop when performing operation I.

Asked on January 19, 2020 in Programming.
Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.