红宝石无符号右移

编程入门 行业动态 更新时间:2024-10-27 17:25:03
本文介绍了红宝石无符号右移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的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).

更多推荐

红宝石无符号右移

本文发布于:2023-10-26 20:37:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531280.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:红宝石   符号

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!