python bytes to C array (like xxd program"

后端 未结 3 2036
自闭症患者
自闭症患者 2021-01-24 07:00

In python3 I have some bytes. I want to export them to C source code. Outside python I use \"xxd -i binary_file\" command.

Example:

x = b\'abc123\'
print         


        
3条回答
  •  野性不改
    2021-01-24 07:39

    In case you want to use caps or not:

    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}
    

提交回复
热议问题