Skip to content

Commit

Permalink
Add bswap method for complex numbers. (JuliaLang#21346)
Browse files Browse the repository at this point in the history
It byte-swaps the real and imaginary parts individually, following
what Fortran compilers do.

The tests read the binary test data from an ad-hoc IOBuffer,
because reinterpret doesn't work for complex numbers.
  • Loading branch information
traktofon authored and stevengj committed Apr 11, 2017
1 parent 64dbcbc commit b7836db
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
3 changes: 3 additions & 0 deletions base/complex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,9 @@ function write(s::IO, z::Complex)
write(s,real(z),imag(z))
end

## byte order swaps: real and imaginary part are swapped individually
bswap(z::Complex) = Complex(bswap(real(z)), bswap(imag(z)))

## equality and hashing of complex numbers ##

==(z::Complex, w::Complex) = (real(z) == real(w)) & (imag(z) == imag(w))
Expand Down
7 changes: 7 additions & 0 deletions test/numbers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2491,6 +2491,13 @@ end
@test reinterpret(Float32,bswap(0x0000c03f)) === 1.5f0
@test bswap(reinterpret(Float64,0x000000000000f03f)) === 1.0
@test bswap(reinterpret(Float32,0x0000c03f)) === 1.5f0
zbuf = IOBuffer([0xbf, 0xc0, 0x00, 0x00, 0x40, 0x20, 0x00, 0x00,
0x40, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xc0, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
z1 = read(zbuf, Complex64)
z2 = read(zbuf, Complex128)
@test bswap(z1) === -1.5f0 + 2.5f0im
@test bswap(z2) === 3.5 - 4.5im

#isreal(x::Real) = true
for x in [1.23, 7, e, 4//5] #[FP, Int, Irrational, Rat]
Expand Down

0 comments on commit b7836db

Please sign in to comment.