Answer the question
In order to leave comments, you need to log in
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 разряда.
long result2 = (long) 128 << 56;
System.out.println(Long.toBinaryString(result2));
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question