如何比较位掩码?

时间:2017-12-08 11:55:47

标签: python binary

我想创建当第一个数字(二进制​​)包含第二个数字(二进制​​)时返回true的函数:

a = '1100'
b = '0101'

返回false但是:

a = '0100'
b = '0101'

返回true

怎么做?

2 个答案:

答案 0 :(得分:1)

您可以先从字符串中创建二进制数,然后对数字执行and (&)并检查输出是否匹配其中任何一个。

In [14]: str_to_bin = lambda x: int(x, 2)
    ...: 
    ...: a = '1100'
    ...: b = '0101'
    ...: a = str_to_bin(a)
    ...: b = str_to_bin(b)
    ...: print a & b in (a, b)
    ...: 
    ...: a = '0100'
    ...: b = '0101'
    ...: a = str_to_bin(a)
    ...: b = str_to_bin(b)
    ...: print a & b in (a, b)
    ...: 
False
True

如果您要专门检查a中是否存在b,请使用条件

print a & b == a

答案 1 :(得分:0)

你可以使用这样的列表理解:

然后以您喜欢的方式将其包装在一个函数中:

a_list = '1100'
b_list = '0101'

# If a value in a_list is '1', remember if the corresponding value in b_list is '1', too 
[b == '1' for a, b in zip(a_list, b_list) if a == '1']
>> [False, True]