摘自convert a string of bytes into an int (python) - Stack Overflow
需求:將形如'y\xcc\xa6\xbb'的byte字符串轉(zhuǎn)化為integer
import struct struct.unpack("L", "y\xcc\xa6\xbb")[0]
若byte串采取大端法:
int.from_bytes(b'y\xcc\xa6\xbb', byteorder='big')
若采取小端法,則:
int.from_bytes(b'y\xcc\xa6\xbb', byteorder='little')
大端法:
s = 'y\xcc\xa6\xbb' num = int(s.encode('hex'), 16)
小端法:
int(''.join(reversed(s)).encode('hex'), 16)
import array integerValue = array.array("I", 'y\xcc\xa6\xbb')[0]
其中I用于表示大端或小端,且使用此方法要注意自己使用的python版本。
如:
sum(ord(c) (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))
又如:
def bytes2int( tb, order='big'): if order == 'big': seq=[0,1,2,3] elif order == 'little': seq=[3,2,1,0] i = 0 for j in seq: i = (i8)+tb[j] return i
ps: CSDN的markdown編輯器好難用,寫到頁面底端就換行錯亂,跳字符。
data_byte1 = int(1324).to_bytes(length=2, byteorder='big', signed=True) #int(參數(shù)):參數(shù)代表要被轉(zhuǎn)換的數(shù)字 #length=2:代表要轉(zhuǎn)換成幾個字節(jié) #byteorder='big'代表高位在前,相反little
data_byte2 = int().from_bytes(data_byte1, byteorder='big', signed=True) print(data_byte1) print(data_byte2)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
標(biāo)簽:江蘇 寧夏 金融催收 云南 酒泉 龍巖 定西 商丘
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python實現(xiàn)byte轉(zhuǎn)integer》,本文關(guān)鍵詞 Python,實現(xiàn),byte,轉(zhuǎn),integer,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。