2

I'm trying to port a Python library to Javascript, but stumbled on a numerical difference between the two..

With Python, 1057618395136 >> 16 == 16137976 With Javascript, 1057618395136 >> 16 == 16120

I read the the integer precision in Javascript is 53 bits, Math.pow(2, 53) == 9007199254740991), which is still in the range of the bifshift operation im trying to do.. What am i missing?

1 Answer 1

4

The JavaScript bitwise operators truncate the floating-point values down to 32-bit integers. Thus, though it is true that a 64-bit floating point value can hold 53-bit integers, you cannot take advantage of all 53 bits with shift operators.

To shift right by 16 bits in JavaScript, you can divide by 65536.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that makes sense! Out of curiosity (i know such micro optimizations are neglectable), is there a difference in performance between the bitshift and the division?
@Martijnh well it's possible that the JavaScript runtime recognizes the fact that you're dividing by a constant that's a power of 2. Most modern hardware (aside from low-end phones) can probably do 64-bit shift operations. Whether any actual implementations do that, I don't know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.