[英]Convert int 32 bits into bool array
我有一個系統 verilog function 我正在嘗試轉換為 python。 function 獲取一個二進制文件並讀入並執行一些 ECC function 檢查輸入是否有效。
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];
...
我的 python 讀取文件並將其轉換為整數列表:
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 function? 我正在使用 python 3.8
如此處所示( https://stackoverflow.com/a/10322018/14226448 )您可以將 int 轉換為如下所示的位數組:
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(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
編輯:不知何故錯過了標題中的“布爾數組”。
由於您使用的是 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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.