python to_bytes()方法,将int转换为bytes
to_bytes()方法
python的int类内置的方法to_bytes(),可以将int类型的数值转换为bytes。to_bytes()可接受三个参数,其语法如下:
语法及参数
to_bytes(self, /, length, byteorder, *, signed=False)
参数解析表:
参数 | 描述 |
---|---|
length | 必须参数,指定to_bytes()方法转换的bytes所占的字节数 |
byteorder | 值为字符串的big或little,指定大端或小端 |
signed | 可选参数,布尔类型值,表示返回值对应的是int有无符号的类型,默认为false |
to_bytes()实例代码
>>> num = (2).to_bytes(2,'little') #记得在2两边加上括号,否则python会抛出SyntaxError
>>> num
b'\x02\x00'
>>> (2).to_bytes(2,'big')
b'\x00\x02'