Home  >  Article  >  Backend Development  >  Why Doesn\'t \"bytes(n)\" Represent the Binary Form of \"n\"?

Why Doesn\'t \"bytes(n)\" Represent the Binary Form of \"n\"?

Linda Hamilton
Linda HamiltonOriginal
2024-10-20 14:54:02620browse

Why Doesn't

Why Doesn't "bytes(n)" Represent Binary?

The "bytes(n)" function in Python 3 generates a byte string of length 'n' filled with null bytes, rather than converting the integer 'n' into its binary representation. This unexpected behavior has its roots in the changes introduced in Python 3.2.

The 'to_bytes' Method

To convert an integer into its binary representation, you can use the 'to_bytes' method introduced in Python 3.2. The following example demonstrates its usage:

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

Alternatively, you can implement your own functions to handle integer-to-byte conversion:

<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>

Signed Integers

The 'to_bytes' method only supports converting unsigned integers. For signed integers, the bit length calculation is more complex:

<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>

The above is the detailed content of Why Doesn\'t \"bytes(n)\" Represent the Binary Form of \"n\"?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn