【问题标题】:Convert int 32 bits into bool array将 int 32 位转换为 bool 数组
【发布时间】:2021-01-19 11:02:19
【问题描述】:

我有一个系统 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];
...

我的 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 功能?我正在使用 python 3.8

【问题讨论】:

  • 1.该函数似乎需要一个 32 位的 int,而不是列表。 2. 在您的代码中,您拥有的是一个列表,我猜您希望将其作为 int 传递给您的函数。 “我如何将 int 转换为 32 位列表以便执行 ECC 函数?”有点困惑? 您能否在您的循环之后发布 list_temp 的样子,以便我们帮助转换那个。
  • @aneroid 我无法发布我的列表,目标是遍历我创建的整数列表并将它们转换为位。每个整数。

标签: python


【解决方案1】:

如此处所示 (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

【讨论】:

    【解决方案2】:

    list_temp 到布尔数组的一个衬线:

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

    其他你可以convert to:

    # 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,那么让我们稍微整理一下阅读内容;并在我们使用 Assignment Expressions 时使用它:

    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.
    

    【讨论】:

    • 我想转换 32 位 int 而不是 8 位
    • 从何而来?您还没有发布list_temp 的示例。我们“猜测”它是 4 个 8 位整数的列表 - 所以你可以得到一个 32 位整数。如果您需要有关如何读取二进制文件以创建 32 位 int 的帮助,请提供该文件的示例和预期结果。
    猜你喜欢
    • 2015-06-12
    • 2011-05-25
    • 2014-07-25
    • 2017-02-24
    • 1970-01-01
    • 2015-12-01
    • 2015-12-01
    • 1970-01-01
    • 2021-01-01
    相关资源
    最近更新 更多