检查位掩码的特定位 [英] Checking specific bits of a bitmask

查看:71
本文介绍了检查位掩码的特定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python中的Bitmasks.据我所知,这些是整数数组,当将它们解压缩为二进制格式时,它们会告诉您为数组中的给定元素设置了32位中的哪一位(= 1).

I am working with Bitmasks in python. As far as I know, these are arrays of integers that when they are unpacked into binary format they tell you which of the 32 bits are set (=1) for a given element in the array.

我想知道最快的方法来检查是否为数组的任何元素设置了4个特定位.我不在乎其余的.我已经尝试了以下解决方案,但是对于我的目的来说还不够快:

I would like to know the fastest way to check whether 4 specific bits are set or not for any element of an array. I do not care about the rest. I have tried the following solution but it is not fast enough for my purpose:

def detect(bitmask, check=(18,22,23,24), bits=32):
    boolmask = np.zeros(len(bitmask), dtype=bool)
    for i, val in enumerate(bitmask):    
        bithost = np.zeros(bits, dtype='i1')
        masklist = list(bin(val)[2:])
        bithost[:len(masklist)] = np.flip(masklist,axis=0)
        if len(np.intersect1d(np.nonzero(bithost)[0] ,check)) != 0:
            boolmask[i] = True        
        else: 
            boolmask[i] = False
    if any(boolmask):
        print("There are some problems")
    else:
        print("It is clean")

例如,如果给定的bitmask包含整数24453656 (1011101010010001000011000 in binary),则功能 detect 的输出将为有一些问题",因为第22位设置为:

For example, if a given bitmask contains the integer 24453656 (1011101010010001000011000 in binary), the output of function detect would be "There are some problems" since bit 22 is set:

bit: ...  20, 21, 22, 23, 24,...  
mask: ... 0,  0,  1,  0,  0,...

关于如何提高性能的任何想法?

Any ideas on how to improve the performance?

推荐答案

整数不过是计算机中的位序列.

Integers are nothing but sequence of bits in the computer.

因此,如果得到整数,则说:333这是计算机的位101001101的序列.它不需要任何拆包.是位.

So, if you get integer, let's say: 333 it is a sequence of bits 101001101 to the computer. It doesn't need any unpacking into bits. It is bits.

因此,如果掩码也是整数,则不需要任何拆包,只需对其进行按位运算即可.请查看维基百科,以了解这些工作原理的详细信息.

Therefore, if the mask is also an integer, you don't need any unpacking, just apply bitwise operations to it. Check wikipedia for details of how these work.

为了检查是否在整数abc中设置了xyz中的任何位,请执行以下操作: (abc & xyz) > 0.如果您绝对需要检查遮罩是否是位的元组,请进行一些打包,如下所示:

In order to check if ANY of the bits xyz are set in an integer abc, you do: (abc & xyz) > 0. If you absolutely need checking mask to be a tuple of bit places, you do some packing, like this:

def detect(bitmask,check=(18,22,23,24)):
    checkmask=sum(2**x for x in check)
    if (bitmask & checkmask) > 0:
        print "There are some problems"
    else:
        print "Everything OK"

请注意,位掩码从基于0的位索引开始.第一位是位0.

Note that bitmasks start with 0 based bit indices. First bit is bit 0.

这篇关于检查位掩码的特定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆