简体   繁体   中英

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?

I searched both the python manual and the inte.net, but can't seem to find anything useful.

I need it to check if an integer is odd (CF=1) or even (CF=0) and divide it by two in one command. 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.

There is no "shift and also return carry flag" operation in Python—or, really, in almost any higher-level language. 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.

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; 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…


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=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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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