将int 32位转换为bool数组



我有一个系统verilog函数,我试图转换成python。该函数接受一个二进制文件,读入并执行一些ECC函数,检查输入是否有效。

function int local_ecc_function(int word_in) ;
int ecc;
ecc[0] = word_in[0 ]^ word_in[1 ]^ word_in[3 ]^ word_in[4 ]^ word_in[6 ]^ word_in[8 ]^ word_in[10 ]^ word_in[11 ]^ word_in[13 ]^ word_in[15 ]^ word_in[17 ]^ word_in[19 ]^ word_in[21 ]^ word_in[23 ]^ word_in[25 ]^ word_in[26 ]^ word_in[28 ]^ word_in[30];
...

my python读取文件并将其转换为int类型的列表:

bytes_arr = f.read(4)
list_temp = []
int_temp = int.from_bytes(bytes_arr, byteorder='big')
while bytes_arr:
bytes_arr = f.read(4)
int_temp = int.from_bytes(bytes_arr, byteorder='big')        
list_temp.append(int_temp)

我如何将int转换为32位列表,以便我可以执行ECC函数?我正在使用python 3.8

如图(https://stackoverflow.com/a/10322018/14226448)所示,您可以像这样将整型转换为位数组:

def bitfield(n):
return [int(digit) for digit in bin(n)[2:]] # [2:] to chop off the "0b" part

如果你想得到一个bool数组,你可以把它强制转换成bool类型:

def bitfield(n):
return [bool(int(digit)) for digit in bin(n)[2:]] # [2:] to chop off the "0b" part

list_temp到bool数组一行:

[bool(int(b)) for num in list_temp for b in bin(num)[2:]]

其他可以转换为:

# without an example of `list_temp`, let's assume it's a list of 4 8-bit ints (<255):
list_temp = [72, 101, 108, 112]
# converting to a string of bits:
bit_str = ''.join(bin(n)[2:] for n in list_temp)
# if you need '112' to be the most-significant, change the line above to:
bit_str = ''.join(bin(n)[2:] for n in list_temp[::-1])
# as an array of bools:
[bool(int(b)) for b in bit_str]
# one-liner version above
# and if you want that all as one large int made up of 1's and 0's:
int(bit_str)
# Output:
# 1001000110010111011001110000
# And if you want what 32-bit integer the above bit-string would be:
int(bit_str, base=2)
# 152663664

编辑:标题中不知何故遗漏了'bool array'。


由于您使用的是Python 3.8,因此让我们稍微清理一下读取;并使用赋值表达式:

list_temp = []
while bytes_arr := f.read(4):
int_temp = int.from_bytes(bytes_arr, byteorder='big')
list_temp.append(int_temp)
# or use a while-True block and break if bytes_arr is empty.

最新更新