How to convert bytearray into integer?

Mark Dickinson dickinsm at
Mon Aug 16 21:36:26 CEST 2010

On Aug 16, 8:08 pm, Jacky <jacky.chao.w... at> wrote:
> Hi Thomas,
> Thanks for your comments!  Please check mine inline.
> On Aug 17, 1:50 am, Thomas Jollans <tho... at> wrote:
> > On Monday 16 August 2010, it occurred to Jacky to exclaim:
> > > Hi there,
> > > Recently I'm facing a problem to convert 4 bytes on an bytearray into
> > > an 32-bit integer.  So far as I can see, there're 3 ways:
> > > a) using struct module,
> > Yes, that's what it's for, and that's what you should be using.
> My concern is that struct may need to parse the format string,
> construct the list, and de-reference index=0 for this generated list
> to get the int out.
> There should be some way more efficient?

Well, you can improve on the struct solution by using the
struct.Struct class to avoid parsing the format string repeatedly:

>>> import struct
>>> S = struct.Struct('<I')
>>> S.unpack_from(buffer(bytearray([1,2,3,4,5])))

This doesn't make a huge difference on my machine (OS X 10.6.4, 64-bit
build of Python 2.6) though;  it's probably more effective for long
format strings. Adding:

def test_struct2(buf, offset, S=struct.Struct('<I')):
    return S.unpack_from(buf, offset)[0]

to your test code, I see a speedup of around 8% over your test_struct.

By the way, you may want to consider using an explicit byte-order/size
marker in your format string;  i.e., use '<I' instead of 'I'.  This
forces a 4-byte little-endian interpretation, regardless of the
platform you're running Python on.


More information about the Python-list mailing list