[Numpy-discussion] byteswapping a complex scalar

Michael Droettboom mdroe@stsci....
Wed Oct 7 10:28:59 CDT 2009

I'm noticing an inconsistency as to how complex numbers are byteswapped 
as arrays vs. scalars, and wondering if I'm doing something wrong.

 >>> x = np.array([-1j], '<c8')
 >>> x.tostring().encode('hex')
# This is a little-endian representation, in the order (real, imag)

# When I swap the whole array, it swaps each of the (real, imag) parts 
 >>> y = x.byteswap()
 >>> y.tostring().encode('hex')
# and this round-trips fine
 >>> z = np.fromstring(y.tostring(), dtype='>c8')
 >>> assert z[0] == -1j

# When I swap the scalar, it seems to swap the entire 8 bytes
 >>> y = x[0].byteswap()
 >>> y.tostring().encode('hex')
# ...and this doesn't round-trip
 >>> z = np.fromstring(y.tostring(), dtype='>c8')
 >>> assert z[0] == -1j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

Any thoughts?


Michael Droettboom
Science Software Branch
Operations and Engineering Division
Space Telescope Science Institute
Operated by AURA for NASA

More information about the NumPy-Discussion mailing list