py3k: converting int to bytes
tjreedy at udel.edu
Thu Feb 24 12:39:13 EST 2011
On 2/24/2011 11:19 AM, spam at uce.gov wrote:
> Is there a better way to convert int to bytes then going through strings:
(This being Py3)
If 0 <= x <= 9, bytes((ord('0')+n,)) will work. Otherwise, no. You would
have to do the same thing str(int) does, which is to reverse the
sequence of remainders from dividing by 10 and then add ord('0') to get
the char code.
Note: an as yet undocumented feature of bytes (at least in Py3) is that
bytes(count) == bytes()*count == b'\x00'*count.
Terry Jan Reedy
More information about the Python-list