How to get an integer from a sequence of bytes

Ned Batchelder ned at nedbatchelder.com
Thu May 30 15:22:26 EDT 2013


On 5/30/2013 2:26 PM, Mok-Kong Shen 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.
>

Presumably you want this to work:

     >>> int(b'\x03')
     3

But you also want this to work:

     >>> int(b'7')
     7

These two interpretations are incompatible.  If b'\x03' becomes 3, then 
shouldn't b'\x37' become 55?  But b'\x37' is b'7', and you want that to 
be 7.

--Ned.

> M. K. Shen
>




More information about the Python-list mailing list