python 把int类型转bytes以及把bytes 转int 类型(使用方法to_bytes ,from_byte, struct)
生活随笔
收集整理的這篇文章主要介紹了
python 把int类型转bytes以及把bytes 转int 类型(使用方法to_bytes ,from_byte, struct)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
把int類型轉(zhuǎn)bytes
方法1 使用方法to_bytes
to_bytes 方法里面有3個參數(shù) ,
第一個數(shù)是指定要轉(zhuǎn)換的bytes占多少個字節(jié)
第二個是byteorder 是指定大端或者是小端 的
第三個是signed參數(shù)表示這個bytes對應(yīng)的是有符號的數(shù),或者無符號的int,這個是boolean值可以不寫
使用to_bytes把1 轉(zhuǎn)化了占2個字節(jié)的bytes ,并且指定大端
num_a = (1).to_bytes(2, "big")
# 或者
# num_a = (168).to_bytes(2, byteorder="big")
print(num_a)
打印結(jié)果
使用to_bytes把1 轉(zhuǎn)化了占2個字節(jié)的bytes ,并且指定小端
num_a = (1).to_bytes(2, "little")
# 或者
# num_a = (168).to_bytes(2, byteorder="little")
print(num_a)
打印結(jié)果:
使用struct
如果對struct 不了解可以點擊查看struct
使用struct把1 轉(zhuǎn)化了占2個字節(jié)的bytes ,并且指定大端
import structnum_a = struct.pack(">h", 1)
print(num_a)
打印結(jié)果
使用struct把1 轉(zhuǎn)化了占2個字節(jié)的bytes ,并且指定小端
import structnum_a = struct.pack("<h", 1)
print(num_a)
打印結(jié)果
把 bytes 轉(zhuǎn)?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])
打印結(jié)果
總結(jié)
以上是生活随笔為你收集整理的python 把int类型转bytes以及把bytes 转int 类型(使用方法to_bytes ,from_byte, struct)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 祝您长寿是谁画的啊?
- 下一篇: python string 转bytes