」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Python 中將整數轉換為位元組字串並返回?

如何在 Python 中將整數轉換為位元組字串並返回?

發佈於2024-11-09
瀏覽:303

How Can I Convert Integers to Byte Strings and Back in Python?

使用「bytes(n)」建立位元組字串

Python 3 中的「bytes(n)」函數不會將整數轉換為其二進位表示形式,而是建立長度為n 的位元組字串,並用空位元組(b'\x00') 填入。此行為源自於 Python 3.2,其中引入了「to_bytes()」方法作為將整數編碼為位元組的方法。

To_Bytes 和To_Bytes

“to_bytes” ()”方法允許將整數明確轉換為字節表示形式,指定字節順序(大端或小端)和長度。

(1024).to_bytes(2, byteorder='big') == b'\x04\x00'

int.from_bytes(b'\x04\x00', 'big' ) == 1024

無符號整數

int.from_bytes(b'\x04\x00', 'big') == 1024

def int_to_bytes(number: int) ->位元組: return number.to_bytes(length=(8 (number (number ;可選[整數]: return int.from_bytes(binary_data, byteorder='big',signed=True)

使用這些函數,您可以對有符號整數與位元組序列進行編碼和解碼。

版本聲明 本文轉載於:1729407016如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3