python – 字节数组到十六进制字符串
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 字节数组到十六进制字符串,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2015字,纯文字阅读大概需要3分钟。
内容图文
![python – 字节数组到十六进制字符串](/upload/InfoBanner/zyjiaocheng/706/3e4c2f0948a042fa9a49014d45bc004d.jpg)
我有数据存储在一个字节数组中.如何将此数据转换为十六进制字符串?
我的字节数组示例:
array_alpha = [ 133, 53, 234, 241 ]
解决方法:
使用str.format:
>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print ''.join('{:02x}'.format(x) for x in array_alpha)
8535eaf1
或使用format
>>> print ''.join(format(x, '02x') for x in array_alpha)
8535eaf1
Note: In the format statements, the
02
means it will pad with up to 2 leading0
s if necessary. This is important since[0x1, 0x1, 0x1] i.e. (0x010101)
would be formatted to"111"
instead of"010101"
或使用bytearray和binascii.hexlify:
>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))
'8535eaf1'
以下是Python 3.6.1中上述方法的基准:
from timeit import timeit
import binascii
number = 10000
def using_str_format() -> str:
return "".join("{:02x}".format(x) for x in test_obj)
def using_format() -> str:
return "".join(format(x, "02x") for x in test_obj)
def using_hexlify() -> str:
return binascii.hexlify(bytearray(test_obj)).decode('ascii')
def do_test():
print("Testing with {}-byte {}:".format(len(test_obj), test_obj.__class__.__name__))
if using_str_format() != using_format() != using_hexlify():
raise RuntimeError("Results are not the same")
print("Using str.format -> " + str(timeit(using_str_format, number=number)))
print("Using format -> " + str(timeit(using_format, number=number)))
print("Using binascii.hexlify -> " + str(timeit(using_hexlify, number=number)))
test_obj = bytes([i for i in range(255)])
do_test()
test_obj = bytearray([i for i in range(255)])
do_test()
结果:
Testing with 255-byte bytes:
Using str.format -> 1.459474583090427
Using format -> 1.5809937679100738
Using binascii.hexlify -> 0.014521426401399307
Testing with 255-byte bytearray:
Using str.format -> 1.443447684109402
Using format -> 1.5608712609513171
Using binascii.hexlify -> 0.014114164661833684
使用格式的方法确实提供了额外的格式化选项,例如用空格分隔数字“”.join,逗号“,”.join,大写打印“{:02X}”.format(x)/ format(x,“02X” )等,但代价是性能影响很大.
内容总结
以上是互联网集市为您收集整理的python – 字节数组到十六进制字符串全部内容,希望文章能够帮你解决python – 字节数组到十六进制字符串所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。