Are bitwise operations on an integer in python processor dependent?

Viewed 140

This answer says that the endianness of an integer in python depends on the processor architecture. Does that imply that bitwise operations like

msg = 0
msg |= 1 << n

yield a different result on different computers, depending on the processor?

A colleague recommended me to use x*2**n instead of x << n because the former is supposed to be platform independent. But I really don't like that because it would obfuscate my intention of setting a specific bit in a message to be sent via a can bus and might require more processing power (I don't know how much optimization the python interpreter is capable of). Would this yield a different result (assuming that both x and n are positive integers)?

1 Answers

Bitwise opertions like this don't depend on the hardware endianess in any language, not even C. These kinds of operations happen after the number has been loaded into a CPU register, at which point the layout in memory doesn't matter. You can think of them essentially as arithmetic operations, like + or -.

So, your colleage is wrong, x << n means the same thing on all platforms. In fact, essentially all of the "basic" Python language works the same on all platforms. Only very platform specific functions in the standard library differ.

One more thing on the shift operation: Python in particular is a little bit special since it has infinite length integers, but << works like you would expect. 1 << 1000 is the same as 2**1000 and in general x << n == x * (2**n) if x and n are integers.

Related