Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

48-bit bitwise operations in Javascript?

I've been given the task of porting Java's Java.util.Random() to JavaScript, and I've run across a huge performance hit/inaccuracy using bitwise operators in Javascript on sufficiently large numbers. Some cursory research states that "bitwise operators in JavaScript are inherently slow," because internally it appears that JavaScript will cast all of its double values into signed 32-bit integers to do the bitwise operations (see here for more on this.) Because of this, I can't do a direct port of the Java random number generator, and I need to get the same numeric results as Java.util.Random(). Writing something like

  this.next = function(bits) {
    if (!bits) {
       bits = 48;
    }
    this.seed = (this.seed * 25214903917 + 11) & ((1 << 48) - 1);
    return this.seed >>> (48 - bits);
  };

(which is an almost-direct port of the Java.util.Random()) code won't work properly, since Javascript can't do bitwise operations on an integer that size.)

I've figured out that I can just make a seedable random number generator in 32-bit space using the Lehmer algorithm, but the trick is that I need to get the same values as I would with Java.util.Random(). What should I do to make a faster, functional port?

like image 994
randomhelp Avatar asked Apr 04 '10 18:04

randomhelp


People also ask

What is bitwise operations in JavaScript?

Bitwise operators treat its operands as a set of 32-bit binary digits (zeros and ones) and perform actions. However, the result is shown as a decimal value. Note: The minimum and the maximum integers that are representable through a 32-bit signed number are -2147483648 to 2147483647.

How bitwise and works in JavaScript?

JavaScript Uses 32 bits Bitwise OperandsBefore a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers. After the bitwise operation is performed, the result is converted back to 64 bits JavaScript numbers. The examples above uses 4 bits unsigned binary numbers.

What is bitwise Anding?

The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.


1 Answers

Instead of foo & ((1 << 48) - 1) you should be able to use foo % Math.pow(2,48).

All numbers in Javascript are 64-bit floating point numbers, which is sufficient to represent any 48-bit integer.

like image 127
brainjam Avatar answered Sep 25 '22 18:09

brainjam