micropython int与bytes之间的转换

bytes转int

b = b'\xff\x01'
x = int.from_bytes(b,'big') #高位在前
x2 = int.from_bytes(b,'little')  #低为在前
print(x)
print(x2)

输出:

65281
511

int转bytes

x = 256
b = x.to_bytes(2,'big')
b1 = x.to_bytes(2,'little')
print(b)
print(b1)

输出:

b'\x01\x00'
b'\x00\x01'

也可以使用bytes函数进行转换,不过只用于0~255之间的整数。

x = [15,255]
b = bytes(x)
print(b)

输出:

b'\x0f\xff'

 

你可能感兴趣的:(micropython)