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