如何在Python 3.4中转换十六进制字符串中的bytestring数组?

时间:2015-08-26 13:27:58

标签: python python-3.4

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

[[18-8-15, 40],[19-8-15, 50],[20-8-15, 50],etc...] //<==== months now one less

如何将此(小端序)转换为十六进制字符串,如:

>>> var
b'\xb5\x1a'

我试过了:

>>> var2
0x1AB5

1 个答案:

答案 0 :(得分:2)

int.from_bytes方法会有所帮助。

  

int.from_bytes(bytes,byteorder,*,signed = False) - &gt; INT

     

返回给定字节数组所表示的整数。

     

...

     

如果byteorder是'little',那么最多   有效字节位于字节数组的末尾。

它会将字节转换为整数:

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对于较长的字节字符串是快速的。