# Fastest way to swap bytes order in-place (ntoh)

**URL:** <https://discourse.julialang.org/t/fastest-way-to-swap-bytes-order-in-place-ntoh/68053>\
**Category:** Performance\
**Created:** [September 12, 2021, 1:54pm UTC](https://discourse.julialang.org/t/fastest-way-to-swap-bytes-order-in-place-ntoh/68053 "2021-09-12T13:54:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [September 12, 2021, 1:54pm UTC](https://discourse.julialang.org/t/fastest-way-to-swap-bytes-order-in-place-ntoh/68053/1 "2021-09-12T13:54:57Z")

</div>

Originally we had

```julia
real_data = ntoh.(reinterpret(T, rawdata))

```

where `T` is some element type such as `Float64`, `rawdata` is always a `UIn8` vector.

After some help from Slack, we’ve moved to:

```julia
real_data = GC.@preserve rawdata ntoh.(unsafe_wrap(Array, Ptr{_eltype}(pointer(rawdata)), dp÷_size))

```

where `dp = length(rawdata)` and `_size = sizeof(_eltype)`.

The latest attemp is to perform `ntoh` manually before `unsafe_wrap` and hopefully getting SIMD since we know every-N bytes to swap ahead of time:

```julia
@inline function fast_ntoh!(rawdata, ::Type{T}) where T
    _size = sizeof(T)
    @inbounds @views @simd for i in 1:_size:length(rawdata) - _size
        r = i:i+_size-1
        rawdata[r] .= rawdata[reverse(r)]
    end
end

```

which doesn’t seem to be fast. I’m wondering if there’s some low-level things we can do to speedup `ntoh` since we know the grouping.

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [September 13, 2021, 12:56am UTC](https://discourse.julialang.org/t/fastest-way-to-swap-bytes-order-in-place-ntoh/68053/2 "2021-09-13T00:56:47Z")

</div>

[https://github.com/JuliaLang/julia/issues/42227](https://github.com/JuliaLang/julia/issues/42227)
