# Converting bytes to floats when byte order is reversed

**URL:** <https://discourse.julialang.org/t/converting-bytes-to-floats-when-byte-order-is-reversed/7585>\
**Category:** General Usage\
**Created:** [December 6, 2017, 11:51pm UTC](https://discourse.julialang.org/t/converting-bytes-to-floats-when-byte-order-is-reversed/7585 "2017-12-06T23:51:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![purplishrock](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/purplishrock/32/13451_2.png) [@purplishrock](https://discourse.julialang.org/u/purplishrock)\
**Post date:** [December 6, 2017, 11:51pm UTC](https://discourse.julialang.org/t/converting-bytes-to-floats-when-byte-order-is-reversed/7585/1 "2017-12-06T23:51:17Z")

</div>

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  
but  
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 ?

Thanks!

edit: what i’m currently doing

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

```

Seems to work…

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [December 7, 2017, 1:29am UTC](https://discourse.julialang.org/t/converting-bytes-to-floats-when-byte-order-is-reversed/7585/2 "2017-12-07T01:29:49Z")

</div>

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

I would suggest

```julia
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.

---

<div class="post-metadata">

**Author:** ![purplishrock](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/purplishrock/32/13451_2.png) [@purplishrock](https://discourse.julialang.org/u/purplishrock)\
**Post date:** [February 21, 2018, 12:35am UTC](https://discourse.julialang.org/t/converting-bytes-to-floats-when-byte-order-is-reversed/7585/3 "2018-02-21T00:35:00Z")

</div>

Hi,

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

Thank you!
