2

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)?

jakun
  • 624
  • 5
  • 13
  • 1
    No. Bit-shifting operations are defined in terms of binary numbers, not in terms of how those numbers are represented in memory in a given architecture. The only case where this makes a difference is when you have an integer value and want to convert it to bytes (e.g. for serialization). If you directly take an integer value and interpret it as an array of bytes (not as easy in Python as it is in C), then the result would differ between little-endian and big-endian architecture. For about any other thing, there is no difference. The recommendation you got is just a more expensive equivalent. – jdehesa Jun 21 '19 at 12:53

1 Answers1

2

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.

Oskar
  • 889
  • 7
  • 20
  • Moreover, a source of this confusion lies in the fact that certain programmers confuse between *value* and *representation* of what is being assigned to a variable; typically, programming languages abstracts away the representation of the given value such that its users (programmers) work with the value assigned to a variable directly, while the representation of the value is only exposed when requested - see [this thread](https://stackoverflow.com/questions/64083189/) for additional background in the context of C. – metatoaster Apr 21 '22 at 13:18