public class Test{
public static void main(String[] args) {
byte i = 31;
System.out.println(i<<3);
}
}
Why does this code print 248,not -8?
public class Test{
public static void main(String[] args) {
byte i = 31;
System.out.println(i<<3);
}
}
Why does this code print 248,not -8?
The output is 256 and it is ok! You shift left it for 3. i is 32, it means 100000 as binary so if you shift left it for 3, it will be 100000000 that means 256 as dec.
After you now edited your question:
byte b = 31
is 0b11111
. If you now do i << 3
this turns to 0b11111000
.
Which is 248
.
You are expecting -8
which would be the result of (byte) (i << 3)
. The result of a bitshift is an integer. You can convert that explicitely to a byte if you want a byte-value.