# Thread: Shifting method using >>

1. Member
Join Date
Nov 2010
Posts
24
Rep Power
0

## 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:

Java 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?

2. Senior Member
Join Date
Feb 2009
Posts
304
Rep Power
6
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.

3. Senior Member
Join Date
Feb 2010
Location
Ljubljana, Slovenia
Posts
470
Rep Power
5
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

4. Member
Join Date
Nov 2010
Posts
24
Rep Power
0
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?

5. Senior Member
Join Date
Feb 2009
Posts
304
Rep Power
6
Yes, but you'd have to play with the methods in the Integer class to get it to work.

Java 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;
}```

6. Senior Member
Join Date
Feb 2010
Location
Ljubljana, Slovenia
Posts
470
Rep Power
5
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.

7. Senior Member
Join Date
Feb 2009
Posts
304
Rep Power
6
That does seem easier... lol

8. Member
Join Date
Nov 2010
Posts
24
Rep Power
0
Thanks a lot, that helps, and the code makes sense. Thanks for your help

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•