python中bytes轉int的實例(bytearray to short int in python)


 python很多數據都是bytes格式的,經常需要轉換成int或者short,筆者實際項目有需求,這里就做個筆記吧。

 

實例一:

bytes轉short:(無符號類型)

 

import struct

barray = b'\x00\xfe\x4b\x00\x4b\x00'
count = len(barray)/2 
integers
= struct.unpack('H'*int(count), barray)

 

注意,這里面的count的長度要是偶數  ,不然會報錯誤.

轉成有符號的,只需要把H改成h即可.

 

實例二:

bytes轉int:

import struct

barray = b'\x00\xfe\x4b\x00\x4b\x00\x22\x44'
count = len(barray)/4 
integers = struct.unpack('i'*int(count), barray)

 

注意,這里面的count的長度要是四的倍數 ,不然會報錯誤.

轉成無符號的,只需要把i改成I即可.

 

參考信息:

 

https://stackoverflow.com/questions/45187101/converting-bytearray-to-short-int-in-python


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM