Converting bytes to floats when byte order is reversed


I’ve got a stream of data that i’m reading which are float values, but each of the 4-bytes in the value are in byte-reversed order.

That means that
1 reinterpret(Float32, x[1:4]) gives me an invalid value
2 reinterpret(Float32, x[4:-1:1]) gives me a valid value

So my plan is to simply create an array of floats and assign each value to result # 2

Can I do that ? I’m not really sure if that is “safe”.
Is there a better way to handle this ?


edit: what i’m currently doing

for i=1:4:n 
  x[i:i+3] = x[i+3:-1:i]
x2 = reinterpret(Float32, x)
return convert(Array{Float64,1}, x2)

Seems to work…


Sounds like your data is in bigendian (“network”) order? There are ntoh and hton functions to help with this.

I would suggest

f = reinterpret(Float32, x)
f .= ntoh.(f)

Note that an expression like x[i:i+3] = x[i+3:-1:i] inside a tight loop is rather inefficient, because each x[i+3:-1:i] allocates a small new temporary array.

If you are reading from a stream, you could also read Float32 values directly, via ntoh(read(io, Float32)) calls.



Well i finally got around to trying your suggestion and the ntoh(read(io, Float32)) was a winner.

Thank you!