programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Left Shift of byte

John Ryan
Ranch Hand
Posts: 124
Hi all,

When a left shift is performed on a byte it is first promoted to an int. When you want the result of the shifted byte value is it true that you must discard the top three bytes of the int result?. Is this because the top three bytes are used only for representing the sign of a byte or a short vaue?

This statement is confusing me because I thought the sign of a byte/short/int was only represented by the right most bit?

Cheers,
John

Stuart Gray
Ranch Hand
Posts: 410
The sign bit is the left-most bit, not the right-most.

John Ryan
Ranch Hand
Posts: 124
Originally posted by John Ryan:
Hi all,

When a left shift is performed on a byte it is first promoted to an int. When you want the result of the shifted byte value is it true that you must discard the top three bytes of the int result?. Is this because the top three bytes are used only for representing the sign of a byte or a short vaue?

This statement is confusing me because I thought the sign of a byte/short/int was only represented by the right most bit?

Cheers,
John

Thanks Stuart, I meant to say left most bit. Is the statement regarding the top three bytes true??

Edwin Dalorzo
Ranch Hand
Posts: 961
Well, you know bytes just have 8 bits. When you shift left the right operand of the shift operator [<<] is promoted to an integer (if it is not a integer already). The right operand is not taken into account for promotion, so it could be a long and would not affect the result.

Now, if the shifted value is assigned back to a byte the upper 16 bits will be discarded.

So, in the next example, when you move the 1 bit to the left, up to the 7th position, then you turn the byte into a negative number.

Hope it helps.
[ June 18, 2005: Message edited by: Edwin Dalorzo ]

John Ryan
Ranch Hand
Posts: 124
Originally posted by Edwin Dalorzo:

Now, if the shifted value is assigned back to a byte the upper 16 bits will be discarded.

Hope it helps.

[ June 18, 2005: Message edited by: Edwin Dalorzo ]

Do you not mean that the upper 24 bytes will be discarded - given that a byte has only 8 bits (32-8 = 24) ??

Edwin Dalorzo
Ranch Hand
Posts: 961
You are right, Mr. Ryan. I did the math wrong. Thanks for the correction.