Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Long getting treated as 32 bits in Java? without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
I am trying to run the following code,
public class MyClass { public static void main(String args[]) { long x = 1 << 39; long l = 537150415L; l = l | x; System.out.println(x); System.out.println(l); } }
This outputs,
128 537150415
I was expecting x
to be a large number. 128
looks like 2^7
, which is 2^(39-32)
. But I thought long is 64 bits.
I am trying to make a bitset of numbers present in set. The numbers can be between 1-60.
JDoodle link – [https://www.jdoodle.com/online-java-compiler#&togetherjs=uH49U5c4Ej]
Answer
The problem is that 1 << 39
is a 32 bit expression. So
long x = 1 << 39;
first calculates a 32 bit value, then sign extends that to a 64 bit value for the assignment.
If you want to create a 64 bit mask, use 1L << 39
.
We are here to answer your question about Long getting treated as 32 bits in Java? - If you find the proper solution, please don't forgot to share this with your team members.