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.
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 "<<".
The Java programming language also provides operators that perform bitwise and bit shift operations on integral types.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With