python字节转换为C数组(例如xxd程序“ [英] python bytes to C array (like xxd program"
本文介绍了python字节转换为C数组(例如xxd程序“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在python3中,我有一些字节。我想将它们导出到C源代码。
在python之外,我使用 xxd -i binary_file命令。
In python3 I have some bytes. I want to export them to C source code. Outside python I use "xxd -i binary_file" command.
示例:
x = b'abc123'
print(bytes_to_c_arr(x))
# should output:
unsigned char x[] = { 0x61, 0x62, 0x63, 0x31, 0x32, 0x33 };
有没有现成的方法或方便的单线?我可以不用类型声明就可以删除内容,只需要内容字节即可。
Is there ready method or handy one-liner? I can do away without type declaration, only bytes for contents would suffice.
推荐答案
如果您不愿使用大写字母:
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}
这篇关于python字节转换为C数组(例如xxd程序“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文