久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Python實現(xiàn)byte轉(zhuǎn)integer

瀏覽:8日期:2022-06-17 15:50:40

摘自convert a string of bytes into an int (python) - Stack Overflow

需求:將形如’yxccxa6xbb’的byte字符串轉(zhuǎn)化為integer

方法 1 導入struct包

import structstruct.unpack('<L', 'yxccxa6xbb')[0]方法 2 python3.2及以上

若byte串采取大端法:

int.from_bytes(b’yxccxa6xbb’, byteorder=’big’)

若采取小端法,則:

int.from_bytes(b’yxccxa6xbb’, byteorder=’little’)方法3 借助十六進制轉(zhuǎn)換

大端法:

s = ’yxccxa6xbb’num = int(s.encode(’hex’), 16)

小端法:

int(’’.join(reversed(s)).encode(’hex’), 16)方法4 使用array包

import arrayintegerValue = array.array('I', ’yxccxa6xbb’)[0]

其中I用于表示大端或小端,且使用此方法要注意自己使用的python版本。

方法5 自己寫函數(shù)實現(xiàn)

如:

sum(ord(c) << (i * 8) for i, c in enumerate(’yxccxa6xbb’[::-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 = (i<<8)+tb[j] return i

ps: CSDN的markdown編輯器好難用,寫到頁面底端就換行錯亂,跳字符。

python int 轉(zhuǎn)byte,byte轉(zhuǎn)int

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)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 福鼎市| 兴城市| 广饶县| 洛南县| 卢龙县| 专栏| 乌拉特后旗| 通海县| 商南县| 沐川县| 常山县| 巴楚县| 城固县| 清远市| 辽中县| 富平县| 平阴县| 谢通门县| 绩溪县| 临沧市| 承德市| 固始县| 织金县| 喀什市| 梨树县| 建宁县| 新乡市| 麻城市| 治县。| 乐山市| 德阳市| 东兴市| 深圳市| 遂宁市| 诏安县| 清水县| 灌阳县| 邢台县| 洮南市| 大新县| 黄骅市|