1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python 把int类型转bytes以及把bytes 转int 类型(使用方法to_bytes from_byte struct)

python 把int类型转bytes以及把bytes 转int 类型(使用方法to_bytes from_byte struct)

时间:2024-06-13 03:34:29

相关推荐

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 structnum_a = struct.pack(">h", 1)print(num_a)

打印结果

使用struct把1 转化了占2个字节的bytes ,并且指定小端

import structnum_a = struct.pack("<h", 1)print(num_a)

打印结果

把 bytes 转int类型

使用 from_bytes 和 unpack

import structprint(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])

打印结果

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。