栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

字节数组到十六进制字符串

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

字节数组到十六进制字符串

使用

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

注意: 在format语句中,

02
表示
0
在必要时最多填充2个前导s。这很重要,因为
[0x1, 0x1, 0x1] i.e.(0x010101)
它将被格式化为
"111"
而不是
"010101"

bytearray
与配合使用
binascii.hexlify

>>> import binascii>>> binascii.hexlify(bytearray(array_alpha))'8535eaf1'

这是Python 3.6.1中上述方法的基准:

from timeit import timeitimport binasciinumber = 10000def 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)).depre('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.459474583090427Using format-> 1.5809937679100738Using binascii.hexlify -> 0.014521426401399307Testing with 255-byte bytearray:Using str.format       -> 1.443447684109402Using format-> 1.5608712609513171Using binascii.hexlify -> 0.014114164661833684

使用的方法

format
的确提供了其他格式选项,例如用空格
" ".join
,逗号
",".join
,大写字母
"{:02X}".format(x)
/
format(x, "02X")
等分隔数字,但是会影响性能。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/641120.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号