I'm trying to understand the bitwise and the shift operators. I wrote a simple code to show me the bits in a short type.
class Shift {
public static void main (String args[]) {
short b = 16384;
for (int t = 32768; t > 0; t = t/2) {
if ((b&t) !=0) System.out.print("1 ");
else System.out.print ("0 ");
}
System.out.println();
b = b+2;
for (long t = 2147483648; t > 0; t = t/2) {
if ((b&t) != 0) System.out.print ("1 ");
else System.out.print ("0 ");
}
System.out.println();
}
}
The output is:
C:\>javac Shift.java
Shift.java:11: error: integer number too large: 2147483648
for (long t = 2147483648; t > 0; t = t/2) {
^
1 error
I don't understand why a long type can't hold the value 2147483648.
Thank you for your help.
Thank you for your answers. I changed the code:
class Shift {
public static void main (String args[]) {
short b = 16384;
for (int t = 32768; t > 0; t = t/2) {
if ((b&t) !=0) System.out.print("1 ");
else System.out.print ("0 ");
}
System.out.println();
b = (short)(b+2);
for (long t = 2147483648L; t > 0; t = t/2) {
if ((b&t) != 0) System.out.print ("1 ");
else System.out.print ("0 ");
}
System.out.println();
}
}
And the output is now:
C:\>java Shift
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0
Why is the output of the second "for" an integer?