7

I have converted JavaScript code which uses bit-wise operators in that code to Python code, but there is one problem when i do this in JavaScript and Python

412287 << 10

then I get this 422181888 same results in both languages. but when i do this in both

424970184 << 10

then i get different results in both of the languages 1377771520 in JavaScript and 435169468416 in Python

can anybody help me with this? any help would be appreciated.

2 Answers 2

6

If you want the JavaScript equivalent value then what you can do is :

import ctypes

print(ctypes.c_int(424970184 << 10 ^ 0).value)

Output:

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

5 Comments

Hi @Achilles thank you for your answer, I have tried this and it is working, will it work for >> operator as well?
Yes,this would get the same overflow behavior as Javascript.
Thanks @Achilles, last question will it work for all bit-wise operators? like ^ operator?
Yes it should work without a problem as it's only limiting the unlimited integer precision of Python.
Thank you @Achilles for your all replies, it helps me a lot.
4

As stated in this SO answer, in javascript the bitwise operators and shift operators operate on 32-bit ints, and your second example overflows the 32 bit capacity, so the python equivalent would be:

(424970184 << 10) & 0x7FFFFFFF

(you get a "modulo"/"masked" value with the signed 32 bit integer mask, not the actual value)

In Python there's no limit in capacity for integers, so you get the actual value.

6 Comments

Afaik, JavaScript uses 54 bits to represent numbers.
but (424970184 << 10) & (2**53-1) yields 435169468416
Ah but the bitwise operators operate on 32 bits. But an int itself has storage for 54 bits.
just checked my self. Thanks for pointing this out, my answer would have been incorrect without that info.
@WillemVanOnsem: JavaScript numbers are actually double-precision (8 byte) floats, not ints. Doubles can represent integers up to 2^53 exactly, just like a 54-bit int could, but that's not what they are.
|

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.