我有一个整数,我知道它的值在0到15之间,即可以用4位表示。我希望将该数组的位表示作为布尔数组获取,即,
0: [False, False, False, False],
1: [True, False, False, False],
2: [False, True, False, False],
# [...]
15: [True, True, True, True]
我该如何最好地实现这一目标?
通过将格式设置为二进制:
def int_to_bool_list(num):
bin_string = format(num, '04b')
return [x == '1' for x in bin_string[::-1]]
或位与:
def int_to_bool_list(num):
return [bool(num & (1<<n)) for n in range(4)]
第一个函数要求将bin_string
内容反转(使用[::-1]
),因为字符串格式化按照我们阅读数字的方式格式化数字 - 首先是最高有效位,而问题要求以最低有效位为顺序。
my_int = 3
[b == '1' for b in bin(my_int)[2:].rjust(4)[::-1]] # Convert, pad and reverse
输出:
[True, True, False, False]
1 2 4 8 = 3
试一下:
Bitmasks = []
Bitmasks.append(int("0001", 2))
Bitmasks.append(int("0010", 2))
Bitmasks.append(int("0100", 2))
Bitmasks.append(int("1000", 2))
myNumber = 12
Bools = []
for bm in Bitmasks:
Bools.append(myNumber|bm==myNumber)
R = 16
list = []
print bin(R)[2:]
for i in bin(R)[2:]:
if (i=="1"):
list.append(True)
else:
list.append(False)
print list
[True, False, False, False, False]
x = 7
strBin = str(bin(x))
lsBoolVal = [i == '1' for i in strBin[2:].zfill(4)]
x=7
在这里只返回了三位。 - Thomas Baruchel