[Numpy-discussion] unpacking bytes directly in numpy

David Cournapeau cournape@gmail....
Sat Sep 26 09:09:36 CDT 2009


On Sat, Sep 26, 2009 at 10:33 PM, Thomas Robitaille
<thomas.robitaille@gmail.com> wrote:
> Hi,
>
> To convert some bytes to e.g. a 32-bit int, I can do
>
> bytes = f.read(4)
> i = struct.unpack('>i', bytes)[0]
>
> and the convert it to np.int32 with
>
> i = np.int32(i)
>
> However, is there a more direct way of directly transforming bytes
> into a np.int32 type without the intermediate 'struct.unpack' step?

Assuming you have an array of bytes, you could just use view:

# x is an array of bytes, whose length is a multiple of 4
x.view(np.int32)

cheers,

David


More information about the NumPy-Discussion mailing list