• Post Reply Bookmark Topic Watch Topic
  • New Topic

Left Shift of byte  RSS feed

 
John Ryan
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The sign bit is the left-most bit, not the right-most.
 
John Ryan
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right, Mr. Ryan. I did the math wrong. Thanks for the correction.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!