Search code examples
javascriptpythonintegersignedbit-shift

Python left shift (sign issue)


In this example I'm obtaining a positive number, but I need an expression in Python that gives the same result as in Javascript.

How can that negative result be obtained in Python?

Python 2.7

mv = 1732584193 << 5

Result:

mv = 55442694176

bin(mv) gives 0b1100111010001010010001100000001

Javascript

mv = 1732584193 << 5

Result:

mv = -391880672

mv.toString(2) gives -10111010110111001111111100000


Solution

  • You could use ctypes to do this:

    >>> import ctypes
    >>> mv = ctypes.c_int32(1732584193)
    >>> mv.value <<= 5
    >>> mv
    c_int(-391880672)
    >>> bin(mv.value)
    '-0b10111010110111001111111100000'