[Numpy-discussion] numpy.ascontiguousarray on byteswapped data !?

Travis Oliphant oliphant.travis at ieee.org
Fri Aug 11 03:12:45 EDT 2006


Sebastian Haase wrote:
> Travis Oliphant wrote:
>> Sebastian Haase wrote:
>>> Hi,
>>> Does numpy.ascontiguousarray(arr) "fix" the byteorder when arr is 
>>> non-native byteorder ?
>>>
>>> If not, what functions does ?
>>>   
>>
>> It can if you pass in a data-type with the right byteorder (or use a 
>> native built-in data-type).
>>
>> In NumPy, it's the data-type that carries the "byte-order" 
>> information.    So, there are lot's of ways to "fix" the byte-order.
>>
> So then the question is: what is the easiest way to say:
> give me the equivalent type of dtype, but with byteorder '<' (or '=') !?
> I would be cumbersome (and ugly ;-) ) if one would have to "manually 
> assemble" such a construct every time ...
Two things.   Every dtype object has the method 
self.newbyteorder(endian) which can be used to either swap the byte 
order or apply a new one to every sub-field.

endian can be '<', '>', '=', 'swap', 'little', 'big'


If you want to swap bytes based on whether or not the data-type is 
machine native you can do something like the following

if not a.dtype.isnative:
    a = a.astype(a.dtype.newbyteorder())

You can make sure the array has the correct data-type using 
.astype(newtype) or array(a, newtype).

You can also set the data-type of the array

a.dtype = newtype

but this won't change anything just how they are viewed. You can always 
byteswap the data explicitly a.byteswap(True) will do it in-place.  So, 
you can change both the data-type and the way it's stored using

a.byteswap(True)                 # Changes the data but not the data-type
a.dtype = a.dtype.newbyteorder()  # changes the data-type but not the data

-Travis









More information about the NumPy-Discussion mailing list