红宝石与javascript中的按位OR [英] Bitwise OR in ruby vs javascript

查看:124
本文介绍了红宝石与javascript中的按位OR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将UID生成器从Javascript转换为Ruby,我想了解以下行为。

Attempting to convert a UID generator from Javascript to Ruby, I wanted to understand the following behavior.

此行代码

89190868196442450 | 0

将在javascript中给出

would give in javascript

1074708816

和红宝石

89190868196442450

我完全理解红宝石如果它存在于eather操作数中,Bitwise OR运算符会复制一些行为,但我仍然对javascript行为感到困惑。
我在javascript整数表示中看得更深,无法找到明确的解释。我发现了这个,但没有完全明白。

I fully understand the ruby behavior as Bitwise OR operator copies a bit if it exists in eather operand, but I'm still puzzled regarding the javascript behavior. I looked deeper in javascript integer representation and could not find a clear explanation. I found this, but did not fully get it.

89190868196442450(二进制)是100111100110111101001111101000000000011101100000101010010,这使得它长57位。

89190868196442450 in binary is 100111100110111101001111101000000000011101100000101010010 which makes it 57 bits length.

任何人都可以给我一个明确的解释或上面的结果。我应该对ruby代码执行哪些操作以确保类似行为?

Could anyone give me a clear explanation or the above result. And what operation should I do on the ruby code to ensure similar behavior?

推荐答案

如果要表示大于32位的数字并在Javascript中对它们执行按位操作,最好使用模拟的长整数,例如: http://closure-library.googlecode.com/svn/docs/class_goog_math_Long.html

If you want to represent numbers with > 32 bits and perform bitwise operations on them in Javascript, you're better off using an emulated long such as this: http://closure-library.googlecode.com/svn/docs/class_goog_math_Long.html.

看一下这个条目。从技术上讲,Javascript可以表示2 ^ 53个整数,但按位运算限制为32位。

Take a look at this entry. Technically Javascript can represent 2^53 ints, but bitwise ops are limited to 32 bits.

什么是JavaScript可以达到的最高整数值而不会丢失精度?

详细说明,当你做什么时,JS会发生什么?89190868196442450 | 0是Javascript取最低有效 32位并将它们与0进行或运算,产生1074708816,而在Ruby中,它与所有位进行或运算。如果由于某种原因你想在Ruby中重现它,你会用1FFFFFFFF和你的数字进行比较,这样你只能在最低有效32位上运行,然后用0运算它(它什么都不做,但会给你相同的结果)。

To elaborate, what's happening in JS when you do 89190868196442450 | 0 is Javascript is taking the least significant 32 bits and ORing them with 0, which yields 1074708816, and in Ruby it is ORing it with all of the bits. If for some reason you wanted to reproduce that in Ruby, you would AND your number with 1FFFFFFFF so you're only operating on the least significant 32 bits and then OR it by 0 (which does nothing but would give you the same result).

这篇关于红宝石与javascript中的按位OR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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