int.to_bytes() for a single byte

jladasky at itu.edu jladasky at itu.edu
Tue Nov 6 23:22:50 EST 2018


On Tuesday, November 6, 2018 at 7:19:09 PM UTC-8, Terry Reedy wrote:
> On 11/6/2018 9:30 PM, j...y at it.u wrote:
> 
> > b = i.to_bytes(1, "big")
> > 
> >Is there another function which provides a more logical interface to this straightforward task?
> 
> Yes
>  >>> 33 .to_bytes(1, 'big')
> b'!'
>  >>> bytes((33,))
> b'!'

Thanks Terry, that's what I was looking for.

I had tried using the bytes() constructor directly, and was getting a byte array of zeros, of the length specified by the integer.  That's in the documentation, and it might be useful, but I haven't seen an obvious use case, and it isn't what I wanted.  Wrapping the integer in a tuple solves the problem of it being interpreted as a length.



More information about the Python-list mailing list