【问题标题】:python bytes to C array (like xxd program"python字节到C数组(如xxd程序)
【发布时间】:2018-03-23 12:14:05
【问题描述】:

在 python3 中,我有一些字节。我想将它们导出到 C 源代码。 在 python 之外,我使用“xxd -i binary_file”命令。

例子:

x = b'abc123'
print(bytes_to_c_arr(x))
# should output:
unsigned char x[] = { 0x61, 0x62, 0x63, 0x31, 0x32, 0x33 };

是否有现成的方法或方便的单线?我可以不用类型声明,只需要内容的字节就足够了。

【问题讨论】:

    标签: python arrays python-3.x byte


    【解决方案1】:
    1. print([hex(i) for in x]) 
    
    2. print(a.hex())
    

    结果将是:

    1. ['0x61', '0x62', '0x63', '0x31', '0x32', '0x33']
    2. '616263313233'
    

    【讨论】:

      【解决方案2】:

      如果您想使用大写字母:

      def bytes_to_c_arr(data, lowercase=True):
          return [format(b, '#04x' if lowercase else '#04X') for b in data]
      
      x = b'abc123'
      print("unsigned char x[] = {{{}}}".format(", ".join(bytes_to_c_arr(x))))
      print("unsigned char x[] = {{{}}}".format(", ".join(bytes_to_c_arr(x, False))))
      
      # output: unsigned char x[] = {0x61, 0x62, 0x63, 0x31, 0x32, 0x33}
      #         unsigned char x[] = {0X61, 0X62, 0X63, 0X31, 0X32, 0X33}
      

      【讨论】:

        【解决方案3】:

        这是一种非常快速的方法(在 Intel i7-8700、Python 2 上为 134 MiB/s),可避免使用缓慢的解释 Python 循环进行迭代并在优化代码中进行迭代

        import binascii
        x=b'abc123'
        hex=binascii.b2a_hex(x)
        # add \x prefix
        hex2=bytearray(4*len(b))
        hex2[0::4]='\\'*len(b)
        hex2[1::4]='x'*len(b)
        hex2[2::4]=hex[0::2]
        hex2[3::4]=hex[1::2]
        

        使用您的示例,这将生成这些十六进制文字

        \x61\x62\x63\x31\x32\x33

        只需将其放在双引号字符串中即可。为简洁起见,我省略了该代码。

        【讨论】:

          猜你喜欢
          • 2014-04-19
          • 2021-01-03
          • 1970-01-01
          • 1970-01-01
          • 2017-10-02
          • 1970-01-01
          • 2021-12-08
          • 2011-07-31
          相关资源
          最近更新 更多