1

Could anyone explain the output of the below program? Appreciate any help in this regard.

Below is my program and its output.

System.out.println("8<<-1 is="+(8<<-1));
System.out.println("8<<-1 is="+(String.format("%32s", Integer.toBinaryString(8<<-1)).replace(' ', '0')));
System.out.println("8<<-2 is="+(8<<-2));
System.out.println("8<<-2 is="+(String.format("%32s", Integer.toBinaryString(8<<-2)).replace(' ', '0')));
System.out.println("8<<-4 is="+(8<<-4));
System.out.println("8<<-4 is="+(String.format("%32s", Integer.toBinaryString(8<<-4)).replace(' ', '0')));

output

8<<-1 is=0
8<<-1 is=00000000000000000000000000000000
8<<-2 is=0
8<<-2 is=00000000000000000000000000000000
8<<-4 is=-2147483648
8<<-4 is=10000000000000000000000000000000
yeppe
  • 679
  • 1
  • 11
  • 43
  • In general it applies that you are not shifting a bit in a negative direction. You does instead shift in the other direction (`8<<-1` => `8>>1` and so on): – patrik Sep 09 '16 at 12:56
  • 1
    @patrik the direction doesn't change. If it did you would have a different answer `8<<-1 == 0` and `8>>1 == 4` – Peter Lawrey Sep 09 '16 at 12:57
  • @PeterLawrey I would guess you have a point, sorry. It is a c++ habit I fear, http://stackoverflow.com/a/4945765/2903371 – patrik Sep 09 '16 at 13:00
  • @patrik Java taking the lower bits is a bit odd imho. – Peter Lawrey Sep 09 '16 at 13:00
  • Is this specifically with Java ?...Sorry guys but I still did not understand why 8<<-1 is=0 8<<-2 is=0 turns out to be zero ...going by this logic (8<<-1 => 8>>1) it should have been 8<<-1 is=4 8<<-2 is=2, correct me if I am wrong. – yeppe Sep 09 '16 at 13:07
  • @yeppe sorry, I would have to retract my comment. It was stupid and I should have kept it, sorry. But anyway keep away from negative shifts. These are nasty. Keep the shift positive so that it makes sence. – patrik Sep 09 '16 at 13:10

0 Answers0