Numpy tobytes() with defined byteorder
Asked Answered
C

1

6

Is it possible to define byte order when converting a numpy array to binary string (with tobytes())?

I would want to force little endianness, but I don't want byte-swapping if it is not necessary.

Chromate answered 11/4, 2019 at 6:57 Comment(2)
You could experiment with astype. Set the desired endedness in the dtype.Merimerida
It seems that generating bytes always involve a copying. In order not to involve another copying when byte-swapping, use a[:,None].view('B')[:,::-1].tobytes() to output opposite-endian (opposite to what's described in the dtype, which is by default little)Huerta
A
6

When interfacing with C code I use this pattern

numpy.ascontiguousarray(x, dtype='>i4')

That dtype string specifies the endianess and precise bit width.

You can check ndarray.flags to see if conversions are necessary.

Atop answered 11/4, 2019 at 7:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.