py3k: converting int to bytes

Terry Reedy tjreedy at udel.edu
Thu Feb 24 18:39:13 CET 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:
>
> x=5
> str(x).encode()

(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 mailing list