• 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: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This question is from khalid mughal page 84.. I could not solve this question.. pls help me with this..
<code>
public class Myclass
{
public static void main(String args[])
{
test(1<<32,"1<<32");
test(1<<31,"1<<31");
test(1<<30,"1<<30");
test(1,"1");
test(0,"0");
test(-1,"-1");
}
public static void test(int i,String exp)
{
if((i >> 1)!= (1>>>1))
System.out.pritln(exp);
}
}

select 2 correct answers :
a> "1<<32"
b> "1<<31"
c> "1"
d> "0"
e> "-1"
</code>
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi anish,
a)If you shift an int x times the actual shifting occurs is x % 32.
Since 32 % 32 = 0, 1<<32 == 1<<0 == 1.
b)Another point to remember is >> and >>> behave same for a positive integer.

1. test(1<<32,"1<<32"); = test(1,"1<<32")// since 1<<32 = 1<<0 = 1

Inside the method i = 1;
i >> 1 and 1 >>>1 gets the same answer due to the point b above
2. test(1<<31,"1<<31")
Here the by shifting 32 times push the first bit to sign bit,makin it negative
thus it will look like 10000000........ To find out the real negative number
take the two's complement which will give -2147483648

inside the method i >> 1 = -1073741824 1>>> 1 =0
thus "1<<31" will be printed
3.test(1<<30,"1<<30");

this will 1<< 30 = 1073741824
inside the method i >>1 = 536870912. Again the condition becomes false and
the string "1<<30" will be printed.

4.test(1,"1"); This is same as case 1.
5.test(0,"0"); This makes the i >> 1 and 1 >>>1 the same
6.test(-1,"-1");
in this case the all the bits are set to one. ie; the bits in -1 = 11111111.....
Thus shifting it right using the signed >> to any number gives the same result -1 itself.
therefore inside test(), it the condition fails and the string "-1" will also be printed.

Thus there will be three answers,"1<<31", "1<<30", "-1"
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic