Note that the shift operators have precedence over the relational operators, so the type of the result is going to be a boolean.

1 << 2 = 4 >> 1 = 2 >>> 2 = 0

So the expression boils down to

so it prints false.

Rohit Nath
Ranch Hand

Joined: Jun 16, 2006
Posts: 387

posted

0

Can you please tell me difference between >> and >>>

>> op1 >> op2 Shifts bits of op1 right by distance op2; fills with highest (sign) bit on the left side >>> op1 >>> op2 Shifts bits of op1 right by distance op2; fills with 0 bits on the left side

What does the bold lettered line mean? "fills with highest (sign) bit"

This essentially boils down to the >> operator leaving the sign of the value shifted the same, i.e. a negative number remains a negative number, and a positive number positive, because the space created at the left of the number after the shift will be filled by the value previously at that location (1 if it was negative, 0 if it was positive) and the >>> operator always making the number positive (by filling the shifted space with a 0)

For example in binary

if we >> shift 1101 by 1 we get 1110 if we >>> shift 1101 by 1 we get 0110

Notice how the sign bit on the second example has altered from 1 to 0.

If you want more information on binary numbers (specifically negative number have a look at Wikipedia here)

Originally posted by Rohit Kharat: Can you please tell me difference between >> and >>>

>> op1 >> op2 Shifts bits of op1 right by distance op2; fills with highest (sign) bit on the left side >>> op1 >>> op2 Shifts bits of op1 right by distance op2; fills with 0 bits on the left side

What does the bold lettered line mean? "fills with highest (sign) bit"

Thx in advance.

Here, "fills with highest(sign) bit" refers to the most significant bit(MSB)(i.e. the left most bit). Both the >> and >>> yields the same result for positive numbers, since the MSB is 0. However, when they are applied to negative numbers, their behavior is completely different.

With >>, the sign bit(i.e. 1) is inserted at the MSB. With >>>, a 0 is inserted at the MSB. So, most often, you always get a positive number.