• 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 ques.

 
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why is the output for the following code i=-1, j=-1.
I would think it should be i=0, j=1.
class Shift {
static int i;
static int j;

public static void main(String args[]){
i=1;
i<<=31;<br /> i>>=31;
i>>=1;
j=1;
j<<=31;<br /> j>>=31;
System.out.print("i="+i );
System.out.print("j="+j);
}
}
 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
here you can see the comments which tell everything to you:
class Shift {
static int i;
static int j;

public static void main(String args[]){
i=1;// 00000000000000000000000000000001
i<<=31; // 10000000000000000000000000000000<br /> i>>=31; // 11111111111111111111111111111111 equi to -1
i>>=1; // 11111111111111111111111111111111 equi to -1
j=1; // 00000000000000000000000000000001
j<<=31; // 10000000000000000000000000000000<br /> j>>=31; // 11111111111111111111111111111111 equi to -1
System.out.print("i="+i );
System.out.print("j="+j);
}
}
 
Ranch Hand
Posts: 242
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Michael,
If you change >>= to >>>= you would get excepted result. i = 0 j = 1. Because >>>= unisgned right shift. Where as >>= is signed right shift.
Santhosh.
 
Michael Burke
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But I thought the signed shift keeps the original sign of the number?
 
Michael Burke
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Maybe I answered my own ques. Does the sign change because the number is shifted 31 places which has the effect of making the most significant bit a 1 thereby changing the sign to negative? I guess this is the exception to the rule that the signed shift keeps the original sign of the number.
reply
    Bookmark Topic Watch Topic
  • New Topic