Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does bit-wise shift left return different results in Python and Java?

I'm trying to port some functionality from a Java app to Python.

In Java,

System.out.println(155 << 24);

Returns: -1694498816

In Python:

print(155 << 24)

Returns 2600468480

Many other bitwise operations have worked in the same way in both languages. Why is there a different result in these two operations?


EDIT: I'm trying to create a function in python to replicate how the left shift operator works in Java. Something along the lines of:

def lshift(val, n):
    return (int(val) << n) - 0x100000000

However this doesn't seem right as (I think) it turns all numbers negatives?


EDIT2: Several hours later, I've decided it is probably not the best idea to use Python for this job and will take part of the Java application and use it as a micro service for the existing Python app.

like image 599
Alex L Avatar asked Feb 23 '16 13:02

Alex L


People also ask

What happens when you shift bits to the left?

When shifting left, the most-significant bit is lost, and a 0 bit is inserted on the other end. The left shift operator is usually written as "<<".

Can you do bit shifting in Java?

The Java programming language also provides operators that perform bitwise and bit shift operations on integral types.

What is the bit wise operator used to shift the values to the left?

The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.

How does Left Shift work in Java?

The left shift means that shift each of the bits is in binary representation toward the left. For example, when we say left shift 5 or 101 by one position. We will shift each of the bits by one position towards the left. So after shifting the number 5 towards the left by one position, the number obtained is 10 or 1010.


1 Answers

Java has 32-bit fixed width integers, so 155 << 24 shifts the uppermost set bit of 155 (which is bit 7, counting bits from zero, because 155 is greater than 27 but less than 28) into the sign bit (bit 31) and you end up with a negative number.

Python has arbitrary-precision integers, so 155 << 24 is numerically equal to the positive number 155 × 224

like image 110
Steve Jessop Avatar answered Sep 21 '22 12:09

Steve Jessop