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

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

Linda Hamilton
Release: 2024-10-20 14:54:02
Original
713 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template