Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   py3k: converting int to bytes (http://www.velocityreviews.com/forums/t744131-py3k-converting-int-to-bytes.html)

 spam@uce.gov 02-24-2011 04:19 PM

py3k: converting int to bytes

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

x=5
str(x).encode()

Thanks.

--
Yves. http://www.SollerS.ca/
http://blog.zioup.org/

 Terry Reedy 02-24-2011 05:39 PM

Re: py3k: converting int to bytes

On 2/24/2011 11:19 AM, spam@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

 John Machin 02-25-2011 02:25 AM

Re: py3k: converting int to bytes

On Feb 25, 4:39*am, Terry Reedy wrote:

> 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"""

 Terry Reedy 02-25-2011 06:50 AM

Re: py3k: converting int to bytes

On 2/24/2011 9:25 PM, John Machin wrote:
> On Feb 25, 4:39 am, Terry Reedy wrote:
>
>> 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"""

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.

--
Terry Jan Reedy

 J. Gerlach 02-26-2011 11:26 AM

Re: py3k: converting int to bytes

Am 24.02.2011 17:19, schrieb spam@uce.gov:
>
> 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...

 J. Gerlach 02-26-2011 11:37 AM

Re: py3k: converting int to bytes

Am 26.02.2011 12:26, schrieb J. Gerlach:
> Am 24.02.2011 17:19, schrieb spam@uce.gov:
>>
>> 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