简体   繁体   English

Python位数组操作

[英]Python bitarray manipulation

I want to remove the least significant 2 bits of every 16-bit integer from a bitarray. 我想从位数组中删除每个16位整数的最低有效2位。 They're stored like this: 它们的存储方式如下:

010101**00**10010101101100**00**10101010.....

(The zeroes between the asterisks will be removed. There are two of them every 16 bits (ignoring the very first)). (星号之间的零将被删除。每16位有两个(忽略第一个)。

I can simply eliminate them with a regular for loop checking indexes (the 7th and 8th after every 16 bits). 我可以使用常规的循环检查索引(每16位之后的第7位和第8位)简单地消除它们。

But... is there another more pythonic way to do this? 但是...还有另一种Python方式可以做到这一点吗? I'm thinking about some slice notation or maybe comprehension lists. 我正在考虑一些切片符号或理解列表。 Perhaps I could divide every number by 4 and encode every one with 14 bits (if there's a way to do that). 也许我可以将每个数字除以4,然后用14位对每个数字进行编码(如果可以的话)。

You can clear bits quite easily with masking. 您可以使用掩膜轻松清除位。 If you want to clear bits 8 and 7 you can do it like this: 如果要清除第8位和第7位,可以这样操作:

a = int('10010101101100',2)
mask = ~((1 << 7) | (1 << 8))
bin(a&mask)

more information about masking from here! 这里获取有关屏蔽的更多信息

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

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