Check out Manning's Countdown to 2014. Use discount code crdotd14 all month for 50% off every deal.
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# bit shift

K Anshul
Ranch Hand

Joined: May 19, 2004
Posts: 71

All operands in the bit shift are promoted to atleast an int (a long if the second operand is long)

What happens is the first operand is a long?
In that case will be an int or a long?
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
If either operand is a long, it will be promoted to a long
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by Chris Allen:
If either operand is a long, it will be promoted to a long

That's not true.

From the JLS, §15.18 Shift Operators:

The type of each of the operands of a shift operator must be a primitive integral type, or a compile-time error occurs. Binary numeric promotion (�5.6.2) is not performed on the operands; rather, unary numeric promotion (�5.6.1) is performed on each operand separately. The type of the shift expression is the promoted type of the left-hand operand.

If you then look into §5.6.1 Unary Numeric Promotion, you'll see this:

Each operand, separately, of the shift operators >>, >>>, and << (�15.18), so that a long shift distance (right operand) does not promote the value being shifted (left operand) to long

Sp, basically, each operand is promoted individually. They do not need to be of the same type in order for the operator to function. You can read my blog entry about bit shifting if you'd like more details.

Corey

SCJP Tipline, etc.
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
Thanks for the correction. If I read your answer correctly, the response to the original correction should be that the left operand (a long) would be shifted by an int as the right operand. Correct? This would mean that only 5 bits would be used in determining the shift (for an int shift operand) instead of 6 (for a long shift operand)?
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
Sorry, meant to add that the number of bits used would apply if the right operand were a negative number.

subject: bit shift