简体   繁体   English

Python的最低有效6位整数

[英]python least significant 6 bits of integer

I'm trying to find the least significant 6 bits of a 16 bit integer. 我正在尝试查找16位整数的最低有效6位。 Let's say my integer is 139 / 0x008B. 假设我的整数是139 / 0x008B。

>>> "{0:b}".format(139)
'10001011'

So the least significant 6 bits are: 因此最低的6位是:

'001011'
>>> int('001011', 2)
11

However, I thought I could do this with the >> operator, but that isn't giving me what I expect: 但是,我以为可以使用>>运算符来执行此操作,但这并没有给我期望的结果:

>>> 139 >> 6
2

Can someone explain the difference between these two? 有人可以解释这两者之间的区别吗?

Shifts are for re-positioning bits, not for isolating them. 移位用于重新定位位,而不是用于隔离它们。 This is called "masking", and in your case you need a bitmask that you "and" with your number. 这称为“屏蔽”,在您的情况下,您需要一个“与”数字的位屏蔽。 This is done with the &-operator in Python. 这是通过Python中的&运算符完成的。 It's fundamentally different from the logical "and"-operator, so don't confuse them! 它与逻辑上的“和”运算符根本不同,因此请不要混淆它们!

>>> bin(139 & 0b111111)
'0b1011'

I think you might want to use the bit-wise 'and' operator ( & ) and not the right-shift operator ( >> ). 我认为您可能想使用按位运算符“与”( & ),而不是向右移运算符( >> )。

Try the following: 139 & 0b111111 请尝试以下方法: 139 & 0b111111

That should give you the 6 least-significant bits. 那应该给您6个最低有效位。

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

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