Skip to main content
 首页 » 编程设计

python之如何在 Python 3.4 中将 bytestring 数组转换为十六进制字符串

2024年10月24日26langtianya

我有一个来自套接字连接的字节串:

>>> var 
b'\xb5\x1a' 

我如何将这个(小端顺序)转换成十六进制字符串,如:

>>> var2 
0x1AB5 

我试过:

>>> var.decode('utf-8') 
Traceback (most recent call last):File "<stdin>", line 1, in <module> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 0: invalid start byte 
 
>>> var.from_bytes(2,'little') 
Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: 'bytes' object has no attribute 'from_bytes' 

请您参考如下方法:

int.from_bytes方法会有所帮助。

int.from_bytes(bytes, byteorder, *, signed=False) -> int

Return the integer represented by the given array of bytes.

...

If byteorder is 'little', the most significant byte is at the end of the byte array.

它将字节转换为整数:

In [1]: int.from_bytes(b'\xb5\x1a', 'little') # 'little' for little-endian order 
Out[1]: 6837 

然后你可以使用hex

In [2]: hex(int.from_bytes(b'\xb5\x1a', 'little')) 
Out[2]: '0x1ab5' 

或format(..., '#x')

In [3]: format(int.from_bytes(b'\xb5\x1a', 'little'), '#x') 
Out[3]: '0x1ab5' 

获取十六进制表示。

其他解决方案包括 base64.b16encode

In [4]: import base64 
 
In [5]: '0x' + base64.b16encode(b'\xb5\x1a'[::-1]).decode('ascii') 
Out[5]: '0x1AB5' 

和binascii.hexlify :

In [24]: '0x' + binascii.hexlify(b'\xb5\x1a'[::-1]).decode('ascii') 
Out[24]: '0x1ab5' 

bytestr = b'\xb5\x1a' 的一些计时:

In [32]: %timeit hex(int.from_bytes(bytestr, 'little')) 
1000000 loops, best of 3: 267 ns per loop 
 
In [33]: %timeit format(int.from_bytes(bytestr, 'little'), '#x') 
1000000 loops, best of 3: 465 ns per loop 
 
In [34]: %timeit '0x' + base64.b16encode(bytestr[::-1]).decode('ascii') 
1000000 loops, best of 3: 746 ns per loop 
 
In [35]: %timeit '0x' + binascii.hexlify(bytestr[::-1]).decode('ascii') 
1000000 loops, best of 3: 545 ns per loop 

对于 bytestr = b'\xb5\x1a' * 100:

In [37]: %timeit hex(int.from_bytes(bytestr, 'little')) 
1000000 loops, best of 3: 992 ns per loop 
 
In [38]: %timeit format(int.from_bytes(bytestr, 'little'), '#x') 
1000000 loops, best of 3: 1.2 µs per loop 
 
In [39]: %timeit '0x' + base64.b16encode(bytestr[::-1]).decode('ascii') 
1000000 loops, best of 3: 1.38 µs per loop 
 
 
In [40]: %timeit '0x' + binascii.hexlify(bytestr[::-1]).decode('ascii') 
1000000 loops, best of 3: 983 ns per loop 

int.from_bytes 对于小字节字符串(可以预见)很快,binascii.hexlify 对于较长字节字符串很快。