Jonathan Edgecombe Jonathan Edgecombe - 8 months ago 42
Java Question

Ruby Unsigned Right Shift

I have a snippet of java code:

return (int)(seed >>> (48 - bits));

As you can see it uses the unsigned right shift operator (>>>). I'm trying to implement this code in ruby which has no unsigned right shift operator, only a signed right shift operator. As I'm not very familiar with the >>> operator I'm not quite sure on how I'd impelemnt this in ruby. I tried doing a few searches to see if anyone had come across this problem before, but couldn't find anything relevent. Any help would be much appreciated :)

Voo Voo

An unsigned shift operator can easily be implemented using simple bit shifting and masking:

public static int unsignedShift(int amt, int val) {
    int mask = (1 << (32 - amt)) - 1;   
    return (val >> amt) & mask;

The mask works by setting all bits to 1 that should be retained after the shift. Note that this returns different results compared to Java for amt >= 32 and amt = 0.