python 把int类型转bytes以及把bytes 转int 类型(使用方法to_bytes ,from_byte, struct)
把int类型转bytes
方法1 使用方法to_bytes
to_bytes 方法里面有3个参数 ,
第一个数是指定要转换的bytes占多少个字节
第二个是byteorder 是指定大端或者是小端 的
第三个是signed参数表示这个bytes对应的是有符号的数,或者无符号的int,这个是boolean值可以不写
使用to_bytes把1 转化了占2个字节的bytes ,并且指定大端
num_a = (1).to_bytes(2, "big")
# 或者
# num_a = (168).to_bytes(2, byteorder="big")
print(num_a)
打印结果
使用to_bytes把1 转化了占2个字节的bytes ,并且指定小端
num_a = (1).to_bytes(2, "little")
# 或者
# num_a = (168).to_bytes(2, byteorder="little")
print(num_a)
打印结果:
使用struct
如果对struct 不了解可以点击查看struct
使用struct把1 转化了占2个字节的bytes ,并且指定大端
import struct
num_a = struct.pack(">h", 1)
print(num_a)
打印结果
使用struct把1 转化了占2个字节的bytes ,并且指定小端
import struct
num_a = struct.pack("<h", 1)
print(num_a)
打印结果
把 bytes 转 int类型
使用 from_bytes 和 unpack
import struct
print(int.from_bytes(b'\x00\x01', "big"))
print(int.from_bytes(b'\x01\x00', "little"))
print(struct.unpack(">h", b'\x00\x01')[0])
print(struct.unpack("<h", b'\x01\x00')[0])
打印结果
还没有评论,来说两句吧...