Ruby Unsigned Right Shift

不问归期 提交于 2019-12-13 18:25:17

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/9071797/ruby-unsigned-right-shift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!