[Numpy-discussion] unpacking bytes directly in numpy

Christopher Barker Chris.Barker@noaa....
Mon Sep 28 11:40:16 CDT 2009


David Cournapeau wrote:
>> 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)

and if you don't have an array, you can use one of:

np.fromstring
np.frombuffer
np.fromfile

they all take a dtype as a parameter. For your example:

 > bytes = f.read(4)
 > i = struct.unpack('>i', bytes)[0]

i = np.fromfile(f, dtype=np.int32, count=1)

and, of course, you cold read a lot more than one number in at once.

-Chris



-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker@noaa.gov


More information about the NumPy-Discussion mailing list