1

I would like to shift this unsigned number: 1479636484000 7 bits to the right. Is this possible in JavaScript?

Both

1479636484000 >> 7

and

1479636484000 >>> 7

returns an incorrect answer (for me). The correct answer should be 11559660031. I guess there's some sign bit involved here, and maybe the number is too large to be supported. But is there any clever way of getting around it?

HelloWorld
  • 3,381
  • 5
  • 32
  • 58
  • Yes, bitwise shifts are possible in JS, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators. Although I'm not sure whether there is a certain syntax to shift a x number of bits. I actually never usesd this functionality. – JJWesterkamp Nov 20 '16 at 15:01
  • Possible duplicate of [How to do bitwise AND in javascript on variables that are longer than 32 bit?](http://stackoverflow.com/questions/3637702/how-to-do-bitwise-and-in-javascript-on-variables-that-are-longer-than-32-bit) – SeinopSys Nov 20 '16 at 15:05
  • I don't think this is a duplicate as this is division and not and. The answer below is not applicable to bitwise and solutions... – HelloWorld Nov 20 '16 at 22:16

2 Answers2

2

Bitwise operations in JavaScript start by truncating the number to a 32-bit integer. Your numbers are too big. The "clever way" to get around that limitation is to implement your own numeric library.

Note that floating-point division by 128 gets you the right answer (if you drop the fraction).

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • ~~(n / 128) does not work. Math.trunc(n / 128) should work, but I don't have ECMA 6, so that doesn't help me. However, n / 128 - n / 128 % 1 does work! Thanks :) – HelloWorld Nov 20 '16 at 17:12
  • You'll have exactly the same problem with the `~` operator as with the bit shift operators - they perform the same 32-bit truncation. `Math.floor()` will drop the fraction from a floating-point value however. – Pointy Nov 21 '16 at 00:28
2

You could use a string with the number and remove the last 7 characters and convert it back to a number.

console.log((1479636484000).toString(2));
console.log((11559660031).toString(2));
console.log((1479636484000).toString(2).slice(0, -7));
console.log(parseInt((1479636484000).toString(2).slice(0, -7), 2));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392