简体   繁体   English

python 处理器中整数的按位运算是否依赖?

[英]Are bitwise operations on an integer in python processor dependent?

This answer says that the endianness of an integer in python depends on the processor architecture. 这个答案说python中整数的字节序取决于处理器架构。 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.一位同事建议我使用x*2**n而不是x << n因为前者应该是平台无关的。 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).但我真的不喜欢那样,因为它会混淆我在通过 can 总线发送的消息中设置特定位的意图,并且可能需要更多的处理能力(我不知道 python 解释器能够进行多少优化)。 Would this yield a different result (assuming that both x and n are positive integers)?这会产生不同的结果吗(假设xn都是正整数)?

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.像这样的按位操作不依赖于任何语言的硬件字节序,甚至 C 也不依赖。这些类型的操作发生在数字被加载到 CPU 寄存器之后,此时内存中的布局并不重要。 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.所以,你的大学错了, x << n在所有平台上都意味着同样的事情。 In fact, essentially all of the "basic" Python language works the same on all platforms.事实上,基本上所有“基本”Python 语言在所有平台上的工作方式都相同。 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.关于移位操作的另一件事:特别是 Python 有点特殊,因为它具有无限长度的整数,但<<像您期望的那样工作。 1 << 1000 is the same as 2**1000 and in general x << n == x * (2**n) if x and n are integers. 1 << 10002**1000相同,通常x << n == x * (2**n)如果 x 和 n 是整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM