# Shifting method using >>

• 11-09-2010, 06:17 PM
ile4
Shifting method using >>
I have a really simple method which is supposed to take 2 ints, x and n, and right shift x by n. This is what I have:

Code:

```public int shiftRight(int x, int n)     {       int shifted = x >> n;       return shifted;     }```
But when I test it, and type in x=1111 and n=2, it gives me 277! When I am expecting to recieve 11. Have I missed something really obvious?
• 11-09-2010, 06:25 PM
StormyWaters
Well, when you pass 1111 as x, the binary value of that is used in the shift.

So 1111's binary is "10001010111"

That shifted right twice is "100010101", and the int value of that is 277.
• 11-09-2010, 06:27 PM
m00nchile
Shift works on binary numbers. If x is 1111 decimal, in binary it's 111000111, shift right by two places, you get 1110001, which is 227 in decimal.
EDIT: my math is rusty, taken to long to reply :D
• 11-09-2010, 06:59 PM
ile4
Oh, I see. Problem is I need it to return the shift of the integer x, because the number thats being put in is a mantissa (the project is all about floating point numbers). So if I input 1111 it needs to output 11. Is there a way I can get it to do this, and return the right shift on the integer, rather than converting it to binary?
• 11-09-2010, 07:03 PM
StormyWaters
Yes, but you'd have to play with the methods in the Integer class to get it to work.

Code:

```        public static int shiftRight(int x, int n) {                 int xOrig = Integer.parseInt(String.valueOf(x), 2);                 int shifted = xOrig >> n;                 shifted = Integer.parseInt(Integer.toBinaryString(shifted));                 return shifted;     }```
• 11-09-2010, 07:08 PM
m00nchile
What about plain and simple integer division? 1111/10 = 111 after all, all you'd need to do was divide by 10 to the power of n, where n is the shift required.
• 11-09-2010, 07:10 PM
StormyWaters
That does seem easier... lol
• 11-09-2010, 07:19 PM
ile4
Thanks a lot, that helps, and the code makes sense. Thanks for your help