红宝石无符号右移 [英] Ruby Unsigned Right Shift

查看:170
本文介绍了红宝石无符号右移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的java code的一个片段:
收益率(INT)(种子>>>(48 - 位));

I have a snippet of java code: return (int)(seed >>> (48 - bits));

正如你可以看到它使用了无符号向右移位运算符(>>>)。我想在Ruby中实现这个code有没有符号向右移位运算符,只有签署右移位运算。由于我不是很熟悉>>>运营商我不是我怎么会impelemnt这红宝石十分肯定。我试着做一些搜索,看看有没有人遇到过这个问题,但找不到任何培训相关。任何帮助将是非常美联社preciated:)

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

推荐答案

如果你想实现一个无符号移位运算,我们可以用一些工作做到这一点:没有,如果有任何我只是觉得自己的简单的解决方案的想法:

If you want to implement an unsigned shift operator we can do this with a bit of work: No idea if there's any simpler solution I just thought of that myself:

public static int unsignedShift(int amt, int val) {
    int lastBit = val & (1 << 31);  // get last bit
    val = val & 0x7fffffff; // clear last bit, ~(1 << 31) could be more efficient
    val >>= amt;   // now we can safely shift signed.
    if (lastBit != 0) {
        val |= 1 << (32 - amt - 1); // set last bit again.
    }
    return val;
}

会好得多,如果是这样!lastBit会工作 - 那么,如果我们就不需要在

Would be much nicer if something like !!lastBit would work - then we wouldn't need the if.

没有关于Ruby的想法,所以你必须端口上面code你自己 - 应该足够简单

No idea about Ruby so you'll have to port the above code yourself - should be simple enough.

编辑:只是想到了一个更简单的方法来做到这一点:(不为0和32正常工作将由JLS的定义 - 也许可以解决的,但最常见如果出现这种情况,无论如何一个bug)

Just thought of a much easier way to do this: (does not work correctly for 0 and 32 which would be defined by the JLS - probably fixable but most often a bug if that happens anyhow)

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

掩模作品通过设置所有位为1应后移被保留(准确地说1转向,应该是0之后,然后通过1减小第一位)。

The mask works by setting all bits to 1 that should be retained after the shift (to be exact shift a 1 to the first bit that should be 0 afterwards and then decrease by 1).

这篇关于红宝石无符号右移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆