[英]Carry bit of python bitwise shift
Is there any way to get the bit that is shifted off by a shift operation in Python, like the carry flag in x86 assembly?有什么办法可以让 Python 中的移位操作移出位,例如 x86 汇编中的进位标志?
I searched both the python manual and the inte.net, but can't seem to find anything useful.我搜索了 python 手册和 inte.net,但似乎找不到任何有用的东西。
I need it to check if an integer is odd (CF=1) or even (CF=0) and divide it by two in one command.我需要它来检查 integer 是奇数 (CF=1) 还是偶数 (CF=0),并在一个命令中将其除以二。 I know that I can mimic the intended behaviour by:
我知道我可以通过以下方式模仿预期的行为:
if x & 1==1: CF=1
else: CF=0
That seems to me as unnecessary coding, or am I expecting to much from python.在我看来,这似乎是不必要的编码,或者我对 python 的期望很高。
There is no "shift and also return carry flag" operation in Python—or, really, in almost any higher-level language. Python中没有“移位和返回进位标志”操作 - 实际上,几乎在任何更高级别的语言中都没有。 Even in C, where
y = x >> 1
compiles to the exact same machine-language op you would have written manually, and you know the carry flag has what you want, there's no way to access it. 即使在C中,
y = x >> 1
也会编译为您手动编写的完全相同的机器语言操作,并且您知道进位标志具有您想要的内容,无法访问它。
However, it's very easy to do this yourself. 但是,自己很容易做到这一点。 Instead of this:
而不是这个:
rest = x>>1
cf = get_carry_flag()
… you do this: … 你做这个:
rest, cf = x>>1, x&1
It's more compact—and probably faster, too. 它更紧凑 - 也可能更快。 Remember, this is Python;
记住,这是Python;
x>>1
isn't translating into a single bit-shift opcode, but into a sequence of bytecodes that the interpreter handles by calling a function that follows a pointer to a linked list representing an arbitrary-length integer and shifts that… x>>1
不是转换为单个位移操作码,而是转换为字节码序列,解释器通过调用一个函数来处理,该函数跟随指向表示任意长度整数的链表的指针并转移...
For shifting the other way, there is no overflow on left-shift, so you have to exclusively %
off the top bit. 对于转移的其他方式,对左移没有溢出,所以你要专门
%
折顶位。 Once you're doing that, remembering the top bit before discarding it isn't much extra burden. 一旦你这样做,在丢弃之前记住最高位并不是额外的负担。
Shift left:左移:
x,bit= x<<1, (x&128)>>7
Shift right:右移:
x,bit= x>>1, x&1
every time you execute it, you get the high or low bit and the "x" shifts每次执行它时,您都会得到高位或低位以及“x”移位
>>> x=0x5a
>>>
>>>
>>> x,bit= x<<1, (x&128)>>7; bit 0
>>> x,bit= x<<1, (x&128)>>7; bit 1
>>> x,bit= x<<1, (x&128)>>7; bit 0
>>> x,bit= x<<1, (x&128)>>7; bit 1
>>> x,bit= x<<1, (x&128)>>7; bit 1
>>> x,bit= x<<1, (x&128)>>7; bit 0
>>> x,bit= x<<1, (x&128)>>7; bit 1
>>> x,bit= x<<1, (x&128)>>7; bit 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.