PYTHON 之 bytes、str和int之间的一些转换

1、bcd和string的相互转换

import binascii
b = b'\x12\x34'
s = binascii.b2a_hex(b).decode()
#b'\x12\x34'->'1234'
 
s = '1234'
b = binascii.a2b_hex(s)
#'1234'->b'\x124'=b'\x12\x34'

2、bytes和int的相互转换

b = b'\x12\x34'
n = int.from_bytes(b,byteorder='big',signed=False)
#b'\x12\x34'->4660
 
n = 4660
b = n.to_bytes(length=2,byteorder='big',signed=False)
#4660->b'\x12\x34'

3、bytes和int[]的相互转换

b = b'\x12\x34'
n = []
for i in b[:]:
    n.append(i)
#b'\x12\x34'->[12,34]
 
n = [12,34]
b = bytes(n)
#[12,34]->b'\x12\x34'

4 bytes和hex字符串之间的相互转换。

到了python 3.5之后,就可以像下面这么干了:

>>> a = 'aabbccddeeff'
>>> a_bytes = bytes.fromhex(a)
>>> print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
>>> aa = a_bytes.hex()
>>> print(aa)
aabbccddeeff
>>>

5 HEX转INT,INT转BYTE, BYTE转字符串

import sys
loginlidar = (0x02, 0x73, 0x4D, 0x4E, 0x20, 0x53, 0x65, 0x74, 0x41, 0x63, 0x63, 0x65, 0x73, 0x73, 0x4D, 0x6F, 0x64, 0x65, 0x20, 0x30, 0x33, 0x20, 0x46, 0x34, 0x37, 0x32, 0x34, 0x37, 0x34, 0x34, 0x03)
b = bytes(loginlidar)
print(loginlidar)
print(len(b))
print(b.decode())
print(len(b.decode()))

输出:
(2, 115, 77, 78, 32, 83, 101, 116, 65, 99, 99, 101, 115, 115, 77, 111, 100, 101, 32, 48, 51, 32, 70, 52, 55, 50, 52, 55, 52, 52, 3)
31
sMN SetAccessMode 03 F4724744
31

6 BYTES
 

发布了138 篇原创文章 · 获赞 80 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/u012308586/article/details/105661856
今日推荐