【问题标题】:how to write array of bits into a file using bytearray如何使用字节数组将位数组写入文件
【发布时间】:2020-06-06 16:58:08
【问题描述】:

我有一个 int 值数组,范围从 0 到 1。即[0,1,1,0,0,1,0,0,1...]。如何使用 bytearray 将其写入文件,其中每个字节包含数组中的 8 个元素(8 位)。 | 和字节标题只是举例:

输出:

| byte 1 | byte 2 | etc...
|01100100|1...    |

011001001...

【问题讨论】:

  • @KennyOstrom 第一个链接无关紧要,这些链接中的答案都没有演示如何使用 bytearray 解决我的问题
  • 显示你的代码,我可以帮忙
  • 呵呵,我想知道最好的方法是什么。我想可以用字节块来完成。我在 struct 模块中找不到任何内容。
  • 你真的需要字节数组吗?

标签: python


【解决方案1】:

这里有一个过度设计的解决方案,仅当列表的元素数量是 8 的倍数时才有效

l = [0,1,1,0,1,1,0,0,
     1,0,1,0,1,1,1,0,
     0,1,0,1,0,1,0,1,
     0,0,1,1,0,0,0,0]

for n in range(len(l)//8):
    print('| byte ', n+1, ' ', sep='', end='')

print('|')

for byte in zip(*[iter(l)]*8):
    print('|', *byte, sep='', end='')

print('|')

出来:

| byte 1 | byte 2 | byte 3 | byte 4 |
|01101100|10101110|01010101|00110000|

【讨论】:

    【解决方案2】:

    由于我必须发布我自己的代码,所以我们开始吧。

    arr = [0,1,1,0,1,1,1,0,1] 
    
    bytearr = bytearray()
    x = ''
    for i in range(len(arr)):
        if i > 0 and i % 8 == 0:
            bytearr.append(int(x,2))
            x = str(arr[i])
        else:
            x += str(arr[i])
    
    # handle remaining bits
    if x != '':
        bytearr.append(int(x,2))
    

    【讨论】:

      【解决方案3】:

      你应该发布你自己的代码,而不是让别人为你写代码,你对我很刻薄。但这听起来对其他人来说是一个有用的问题,所以你去吧:

      (迟到一周,以防万一这是作业)

      # helper function with some basic math
      def number(digits, base):
          value = 0
          for digit in digits:
              value *= base
              value += int(digit)
          return value
      
      if 826 != number('826', 10):
          raise ValueError
      
      if 64+16+2+1 != number([0, 1, 0, 1, 0, 0, 1, 1], 2):
          raise ValueError
      
      # helper function to break the data up into the expected chunks
      # https://stackoverflow.com/a/312464/1766544
      def chunks(arbitrary_list, chunk_size):
          for i in range(0, len(arbitrary_list), chunk_size):
              yield arbitrary_list[i:i + chunk_size]
      
      data = [
          0, 0, 0, 0, 0, 0, 0, 0,
          0, 0, 0, 0, 0, 0, 0, 1,
          0, 0, 0, 0, 0, 0, 1, 0,
          0, 0, 0, 0, 0, 1, 0, 0,
          0, 0, 0, 0, 1, 0, 0, 0,
          0, 0, 0, 1, 0, 0, 0, 0,
          0, 0, 1, 0, 0, 0, 0, 0,
          0, 1, 0, 0, 0, 0, 0, 0,
          1, 0, 0, 0, 0, 0, 0, 0,
      ]
      
      # the bytearray constructor needs an iterable
      # the iterable needs to yield the number
      # the number needs 8 bits at a time
      binary_data = bytearray((number(bits, base=2) for bits in chunks(data, 8)))
      
      # write the bytearray to a file is too easy
      # there's already a function that writes stuff to a file
      #with open ('filename.data', 'wb') as f:
          #f.write(binary_data)
      
      # but easier to demonstrate that we have the right values like so:
      for n in binary_data:
          print(n)
      

      输出:

      0
      1
      2
      4
      8
      16
      32
      64
      128

      【讨论】:

      • 对你意味着什么?去给妈妈哭。接受一些批评,认为您的链接没有用,然后继续前进。如果您不打算提供帮助,也许不要留在网站上
      • 也仅供参考,数字不是函数。 name 'number' is not defined
      猜你喜欢
      • 2014-04-10
      • 2019-02-07
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多