How to get an integer from a sequence of bytes

Mok-Kong Shen mok-kong.shen at t-online.de
Sun Jun 2 15:25:45 EDT 2013


Am 30.05.2013 21:22, schrieb Ned Batchelder:
>
> 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.

b'7' is the byte with the character 7 in a certain code, so that's
ok. In other PLs one assigns an int to a byte, with that int in either
decimal notation or hexadecimal notation, or else one assigns a
character to it, in which case it gets the value of the character
in a certain code. What I don't yet understand is why Python is
apprently different from other PLs in that point in not allowing direct
coersion of a byte to an int.

M. K. Shen





More information about the Python-list mailing list