Bitwise OR in ruby vs javascript

后端 未结 1 1326
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 06:17

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

this line of code

89190868196442450 | 0


        
相关标签:
1条回答
  • 2021-01-21 06:30

    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.

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

    What is JavaScript's highest integer value that a Number can go to without losing precision?

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

    0 讨论(0)
提交回复
热议问题