py3k: converting int to bytes

G

Guest

Is there a better way to convert int to bytes then going through strings:

x=5
str(x).encode()


Thanks.
 
T

Terry Reedy

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

John Machin

Note: an as yet undocumented feature of bytes (at least in Py3) is that
bytes(count) == bytes()*count == b'\x00'*count.

Python 3.1.3 docs for bytes() say same constructor args as for
bytearray(); this says about the source parameter: """If it is an
integer, the array will have that size and will be initialized with
null bytes"""
 
T

Terry Reedy

Python 3.1.3 docs for bytes() say same constructor args as for
bytearray(); this says about the source parameter: """If it is an
integer, the array will have that size and will be initialized with
null bytes"""

Yes, it is there in the builtin functions section, but not in the doc
strings. I opened an issue to fix the latter (#11310), with a proposed
patch.
 
J

J. Gerlach

Am 26.02.2011 12:26, schrieb J. Gerlach:
Am 24.02.2011 17:19, schrieb (e-mail address removed):
Is there a better way to convert int to bytes then going through strings:

x=5
str(x).encode()


Thanks.
bytes([8])
b'\x08'
seems more straight forward...
.... but it gives a different result. I should've tested before
answering, sorry.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top