• 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

shift >>operators

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
code:
class Test
{
public static void main(String arg[])
{
byte i=-42;
int n=i>>4;//line1 -42/2power4
byte l=12;
int m=12>>4;//line2 12/2power4
byte j=34;
int k=j>>3;//line3 34/2power3
System.out.println(n+""+m+""+k);
}
}
output:-3 //-42/2power4 //confuse
:0// 12/2power4 //ok
:4 //34/2power3 //ok
Respected sir
for line1 after calculation
how this result come -3 i think it -2.If
i performe this with 42 the
result is 2, is the result is round.
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The answer is -3.
There is difference in representing negative values in binary.
To represent -42 in bits you have to calculate the 2's complement of the number. ie., invert the digits and add 1.
42 = 00101010
Invert bits = 11010101
add 1 = 11010110
ie., -42 = 11010110
-42 >> 4 = 11111101 = -3
Since the most significant bit in the result is 1, again you have to convert it into 2's complement and add the negative sign.
ie, 2's complement = 00000010
1
--------
00000011 = 3
--------
Result is -3.
 
Ranch Hand
Posts: 400
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
a good shortcut is that ~x is always -(x)-1
 
reply
    Bookmark Topic Watch Topic
  • New Topic