Java shift operator

Consider the following Java code:

byte a = -64; System.out.println(a << 1); 

The output of this code is -128

I tried to understand why this is the result:

64 = 0 1000000 (MSB - sign bit)

-64 = 1 1000000 (towing format)

The expected result after the switch: 1 000 000 (This is 0, because the MSB is only a sign bit)

Please explain what I am missing.

+4
source share
7 answers

Two additional representations -128 - 10,000,000, so your results are correct.

+3
source
 10000000 is -128 10000001 is -127 10000010 is -126 ... 

So 10000000 not 0 . This is -128 , which was your way out.

+2
source

This program

 System.out.println(Integer.toBinaryString(-64)); System.out.println(Integer.toBinaryString(-64 << 1)); System.out.println("-64 << 1 = " + (-64 << 1)); 

prints

 11111111111111111111111111000000 11111111111111111111111110000000 -64 << 1 = -128 

You can see that -64 <1 matches -64, except that all bits are left-shifted by 1 (the least significant bit becomes 0)

+2
source

In the operator shift, the sign of the bit is ignored. So 1 1,000,000 <1 is 10,000,000, which is -128.what is the problem?
Our machines use two additions to represent numbers (signed and unsigned). To represent a negative machine, a number negates a positive value and adds 1.
-128 is! 10000000 + 1 = 01111111 + 1 = 10000000
EDIT:
I was wrong, only the shift-shift operator ignored the sign bit. 10100000 <1 == 01000000
For unsigned offsets, there is a โ†’> operator on the right, which also shifts the sign bit.
11000000 โ†’ 1 == 10100000 and 11000000 โ†’> 1 == 01100000

+1
source

In two additions, MSB is not just a bit of a sign, do you think this is possible? In 8 bit two additions,

10000000 = 0x80 = -128

+1
source

<< means 2 times

>> means division by 2

And, during shift operations, do not consider the signed bit.

0
source

I am curious. << 1 (ignoring all the details) "multiplied by 2." -64 * 2 = -128. So why do you think it's really -128?

0
source

Source: https://habr.com/ru/post/1395557/


All Articles