-4

Below are some javascript codes

a >>> (c -= 8)) % 256
a = (a << 6) + f

Is there any shortcut equivalent codes for those lines in Python?

2 Answers 2

1

There is no zero filled right shift operator >>> in python and we can not use short hand assignment operator in expressions (like c -= 8). So it can be written like this

(a >> (c - 8)) % 256
a = (a << 6) + f
Sign up to request clarification or add additional context in comments.

5 Comments

So instead of >>> if i use >> and << should result the same?
@AbulHasnat Nope. Python handles negative numbers differently. So, >> itself is enough.
(a & 0xffffffff) >> (c - 8)) % 256 should be used to get the same result with the javascript expression.
@falsetru Why to restrict to 32 bits?
Try -1 >> 1 and -1 >>> 1 in javascript. Bitwise operators in Javascript treat their operands as a sequence of 32 bits according to Bitwise Operators - Javascript
0

Yes, there is. Python Bitwise Operators.

From the Docs:

The Operators:

x << y

Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

x >> y

Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.

x & y

Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.

x | y

Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.

~ x

Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.

x ^ y

Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.