How to get an integer from a sequence of bytes

jmfauth wxjmfauth at gmail.com
Thu May 30 14:53:15 EDT 2013


On 30 mai, 20:42, Ian Kelly <ian.g.ke... at gmail.com> wrote:
> On Thu, May 30, 2013 at 12:26 PM, Mok-Kong Shen
>
> <mok-kong.s... at t-online.de> wrote:
> > Am 27.05.2013 17:30, schrieb Ned Batchelder:
>
> >> On 5/27/2013 10:45 AM, Mok-Kong Shen wrote:
>
> >>> From an int one can use to_bytes to get its individual bytes,
> >>> but how can one reconstruct the int from the sequence of bytes?
>
> >> The next thing in the docs after int.to_bytes is int.from_bytes:
> >>http://docs.python.org/3.3/library/stdtypes.html#int.from_bytes
>
> > I am sorry to have overlooked that. But one thing I yet wonder is why
> > there is no direct possibilty of converting a byte to an int in [0,255],
> > i.e. with a constrct int(b), where b is a byte.
>
> The bytes object can be viewed as a sequence of ints.  So if b is a
> bytes object of non-zero length, then b[0] is an int in range(0, 256).

----

Well, Python now "speaks" only "integer", the rest is
commodity and there is a good coherency.

>>> bin(255)
'0b11111111'
>>> oct(255)
'0o377'
>>> 255
255
>>> hex(255)
'0xff'
>>>
>>> int('0b11111111', 2)
255
>>> int('0o377', 8)
255
>>> int('255')
255
>>> int('0xff', 16)
255
>>>
>>> 0b11111111
255
>>> 0o377
255
>>> 255
255
>>> 0xff
255
>>>
>>> type(0b11111111)
<class 'int'>
>>> type(0o377)
<class 'int'>
>>> type(255)
<class 'int'>
>>> type(0xff)
<class 'int'>

jmf



More information about the Python-list mailing list