擅长:python、mysql、java
<p>在Python3.2中,您可以</p>
<pre><code>>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
</code></pre>
<p><a href="https://docs.python.org/3/library/stdtypes.html#int.to_bytes" rel="noreferrer">https://docs.python.org/3/library/stdtypes.html#int.to_bytes</a></p>
<pre><code>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></pre>
<p>因此,<code>x == int_from_bytes(int_to_bytes(x))</code>。请注意,此编码仅适用于无符号(非负)整数。</p>