[Numpy-discussion] Functions to pack/unpack bytes?

Zachary Pincus zachary.pincus@yale....
Wed Jul 29 08:35:11 CDT 2009


> Does numpy have functions to convert between e.g. an array of uint32  
> and
> uint8, where the uint32 array is a packed version of the uint8 array
> (selecting little/big endian)?


You could use the ndarray constructor to look at the memory differently:

In : a = numpy.arange(240, 260, dtype=numpy.uint32)
In : a
Out:
array([240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252,
        253, 254, 255, 256, 257, 258, 259], dtype=uint32)

In : b = numpy.ndarray(shape=(len(a)*4,), dtype=numpy.uint8, buffer=a)

In : b
Out:
array([240,   0,   0,   0, 241,   0,   0,   0, 242,   0,   0,   0, 243,
          0,   0,   0, 244,   0,   0,   0, 245,   0,   0,   0, 246,   0,
          0,   0, 247,   0,   0,   0, 248,   0,   0,   0, 249,   0,   0,
          0, 250,   0,   0,   0, 251,   0,   0,   0, 252,   0,   0,   0,
        253,   0,   0,   0, 254,   0,   0,   0, 255,   0,   0,   0,   0,
          1,   0,   0,   1,   1,   0,   0,   2,   1,   0,   0,   3,   1,
          0,   0], dtype=uint8)


I assume for selecting little/big-endian going the other way, you  
could use the other methods of specifying dtypes that allow for byte- 
order descriptors. (Like dtype objects or the format strings.)

Zach


More information about the NumPy-Discussion mailing list