How to get an integer from a sequence of bytes

Carlos Nepomuceno carlosnepomuceno at outlook.com
Mon May 27 20:37:37 EDT 2013


----------------------------------------
> From: steve+comp.lang.python at pearwood.info
> Subject: Re: How to get an integer from a sequence of bytes
> Date: Mon, 27 May 2013 15:00:39 +0000
> To: python-list at python.org
>
> On Mon, 27 May 2013 16:45:05 +0200, 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?
>
> Here's one way:
>
> py> n = 11999102937234
> py> m = 0
> py> for b in n.to_bytes(6, 'big'):
> ... m = 256*m + b
> ...
> py> m == n
> True
>
>
> --
> Steven
>
> --
> http://mail.python.org/mailman/listinfo/python-list

Python 2 doesn't have to_bytes()! :(

# Python 2, LSB 1st
def to_lil_bytes(x):
    r = []
    while x != 0:
        r.append(int(x & 0b11111111))
        x>>= 8
    return r

# Python 2, LSB 1st
def from_lil_bytes(l):
    x = 0
    for i in range(len(l)-1, -1, -1):
        x <<= 8
        x |= l[i]
    return x

# Python 2, MSB 1st
def to_big_bytes(x):
    r = []
    while x != 0:
        r.insert(0, int(x & 0b11111111))
        x>>= 8
    return r

# Python 2, MSB 1st
def from_big_bytes(l):
    x = 0
    for i in range(len(l)):
        x <<= 8
        x |= l[i]
    return x

Can it be faster? 		 	   		  


More information about the Python-list mailing list