3

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

this line of code

89190868196442450 | 0

would give in javascript

1074708816

and in ruby

89190868196442450

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 in binary is 100111100110111101001111101000000000011101100000101010010 which makes it 57 bits length.

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?

Community
  • 1
  • 1
jlamberc
  • 85
  • 8
  • 3
    When you do bitwise operations in JavaScript the arguments get converted to a signed 32-bit integer. Because 89190868196442450 is larger than the largest signed 32-bit int (2147483647) , you don't get the expect results – NullUserException Feb 15 '13 at 16:31

1 Answers1

3

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

Community
  • 1
  • 1
lmortenson
  • 1,610
  • 11
  • 11