• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question on Unsigned Right Shift Operator

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have the following code which generates the output = -7. Can anyone explain me how. Thanks.

 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class UnsignedRightShift{
public static void main(String[] args){
byte b = -13;
b >>>=1;
System.out.println(b);
}
}

Here "b>>>=1;" is the same as "b = (byte)(b>>>1);"

Anything smaller than an int is promoted to an int, so b promoted to int which is "fffffff3"; and it is "7ffffff9" after shift. Then it casts int to byte which is "f9" (-7).

Please see 15.19 Shift Operators:


The type of each of the operands of a shift operator must be a type that is convertible (�5.1.8) to 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 (�) is performed on each operand separately. The type of the shift expression is the promoted type of the left-hand operand.


[ June 01, 2006: Message edited by: wise owen ]
 
Sharn Arora
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks, Wise
 
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
after casting from int to byte chnaged it to "F9"

but how "F9" is -7??

can you please explain this???
 
Sharn Arora
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
F9 when converted to binary, becomes 11111001 which is a negative number since the most significant bit is 1. Use 2's complement (flip all bits & add 1) to get the actual decimal value.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic