首頁  >  文章  >  後端開發  >  為什麼「bytes(n)」不代表「n」的二進位形式?

為什麼「bytes(n)」不代表「n」的二進位形式?

Linda Hamilton
Linda Hamilton原創
2024-10-20 14:54:02620瀏覽

Why Doesn't

為什麼「bytes(n)」不代表二進位?

Python 3 中的「bytes(n)」函數產生長度為 'n 的位元組字串' 填滿空字節,而不是將整數 'n' 轉換為其二進位表示。這種意外行為的根源在於 Python 3.2 中引入的變更。

「to_bytes」方法

要將整數轉換為其二進位表示形式,可以使用中引入的「to_bytes」方法Python 3.2。以下範例示範了其用法:

<code class="python">>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'</code>

或者,您可以實現自己的函數來處理整數到位元組的轉換:

<code class="python">def int_to_bytes(x: int) -> bytes:
    return x.to_bytes((x.bit_length() + 7) // 8, 'big')

def int_from_bytes(xbytes: bytes) -> int:
    return int.from_bytes(xbytes, 'big')</code>

有符號整數

'to_bytes' 方法僅支援轉換無符號整數。對於有符號整數,位長計算較為複雜:

<code class="python">def int_to_bytes(number: int) -> bytes:
    return number.to_bytes(length=(8 + (number + (number < 0)).bit_length()) // 8, byteorder='big', signed=True)

def int_from_bytes(binary_data: bytes) -> Optional[int]:
    return int.from_bytes(binary_data, byteorder='big', signed=True)</code>

以上是為什麼「bytes(n)」不代表「n」的二進位形式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn