B
B
Biaci_Anj2021-12-10 17:44:13
Java
Biaci_Anj, 2021-12-10 17:44:13

Why do bit shifts work this way in Java?

Let's imagine that we have a task to place a one in place 1 and 63 zeros after.
Those. do something like this 1
10000000000000000000000000000000000000000000000000000000000

For example, let's try to shift 1 by 64 positions.

long result = (long) 1 << 64;
        System.out.println(Long.toBinaryString(result)); // получаем единицу, логично. Long положительный может иметь 63 разряда.

Let's try to work around this problem.
long result2 = (long) 128 << 56;
        System.out.println(Long.toBinaryString(result2));

And we get the desired result
100000000000000000000000000000000000000000000000000000000000
.

The question is, why can we do this with the method above, but just 1 << 64 in any way?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vamp, 2021-12-11
@Biaci_Anj

The bit shift for a long type cannot exceed 63. Therefore, a shift of 1L << 64 will be converted by jvm to 1L << (64 & 0x3f), resulting in 1L << 0, and therefore your value does not change in the final.
The shift 1L << 63 solves your problem. The unit is initially at position 1 (positions are numbered from right to left) and shifted to the left by 63 positions. You get the desired 1 by 64 positions with 63 zeros behind.
As for 128L << 56, everything is correct and logical here. The unit is in the 8th position and has 7 zeros behind. Shifting it 56 positions, you get the desired result - one by 64 positions (8 + 56) and 63 zeros behind (7 zeros + 56).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question