我们在使用Python的过程中,会遇到这种情况:需要将接收的bytes数据转换为整形数,或者是将整形数转换成bytes数据。之前小编介绍过在Python中可以转换为整形数的int函数。本文小编就介绍Python中int与bytes如何相互转换的过程:int.to_bytes()和int.from_bytes()。

python int 转字符 python int转字节_leetcode

1、int.to_bytes()

def intToBytes(value, length):

    result = []

    for i in range(0, length):

        result.append(value >> (i * 8) & 0xff)

    result.reverse()

    return result

2、int.from_bytes()

1 # bytes 与 int 

2 b=b'\x01\x02' 

3 num=int.from_bytes(b,'little') 

4 print('bytes转int:',num)

输出

513

以上就是Python中int与bytes相互转换的过程,只需简单的转换就可以得到我们想到的数据类型,是不是挺方便的呢?快用起来吧~