Bitwise endian swap for various types

前端 未结 4 1639
感情败类
感情败类 2020-12-03 12:02

With the help of various sources, I have written some SwapBytes methods in my binary reader class that swap endian in ushort, uint, an

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 12:36

    Just add a cast to unsigned at the start and back to signed at the end.

    public long SwapBytes(long value)
    {
        return (long)SwapBytes((ulong)value);
    }
    

    It might be necessary to manually inline the call to SwapBytes for maximal performance.


    On a different note, you might want to avoid swapping, in favour of directly reading the data from the original byte array in the desired endianness. See Efficient way to read big endian data in C# for details.

提交回复
热议问题