Results 1 to 8 of 8
Thread: Shifting method using >>
 11092010, 05:17 PM #1Member
 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; }
 11092010, 05:25 PM #2Senior Member
 Join Date
 Feb 2009
 Posts
 312
 Rep Power
 12
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.
 11092010, 05:27 PM #3Senior Member
 Join Date
 Feb 2010
 Location
 Ljubljana, Slovenia
 Posts
 470
 Rep Power
 11
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 :DEver seen a dog chase its tail? Now that's an infinite loop.
 11092010, 05:59 PM #4Member
 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?
 11092010, 06:03 PM #5Senior Member
 Join Date
 Feb 2009
 Posts
 312
 Rep Power
 12
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; }
 11092010, 06:08 PM #6Senior Member
 Join Date
 Feb 2010
 Location
 Ljubljana, Slovenia
 Posts
 470
 Rep Power
 11
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.
Ever seen a dog chase its tail? Now that's an infinite loop.
 11092010, 06:10 PM #7Senior Member
 Join Date
 Feb 2009
 Posts
 312
 Rep Power
 12
That does seem easier... lol
 11092010, 06:19 PM #8Member
 Join Date
 Nov 2010
 Posts
 24
 Rep Power
 0
Similar Threads

Shifting String Letters
By DreamNaut in forum New To JavaReplies: 3Last Post: 10262010, 08:12 PM 
Q about shifting data in an array
By alihht in forum New To JavaReplies: 7Last Post: 02032010, 06:17 AM 
Bit Wise operation: shifting
By rueter in forum New To JavaReplies: 1Last Post: 06272009, 06:51 AM 
Shifting characters in array
By Mayur in forum New To JavaReplies: 2Last Post: 04242009, 10:19 PM 
[SOLVED] Shifting an array
By VeasMKII in forum New To JavaReplies: 2Last Post: 02042009, 06:18 PM
Bookmarks