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'

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.