Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between JavaScript bit-wise operator code and Python bit-wise operator code

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.

like image 717
VASIM SETA Avatar asked Jan 12 '17 10:01

VASIM SETA


People also ask

What is a bitwise operator 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.

What is a bitwise operator in Python?

Python bitwise operators are used to perform bitwise calculations on integers. The integers are converted into binary format and then operations are performed bit by bit, hence the name bitwise operators. Python bitwise operators work on integers only and the final output is returned in the decimal format.

What is the difference between logical and bitwise operators in Python?

The logical AND operator works on Boolean expressions, and returns Boolean values only. The bitwise AND operator works on integer, short int, long, unsigned int type data, and also returns that type of data.

What are the different bitwise operators?

AND, OR, XOR, NOT, SHIFT, and MASK are the 6 bitwise operators. Each bit in the number is regarded as a 0 or 1 by the operators, which work with the binary representation of numbers.


2 Answers

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
like image 81
Taufiq Rahman Avatar answered Oct 07 '22 01:10

Taufiq Rahman


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.

like image 35
Jean-François Fabre Avatar answered Oct 07 '22 01:10

Jean-François Fabre