Bitwise endian swap for various types

前端 未结 4 1638
感情败类
感情败类 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:38

    Instead of conceptually deconstructing to separate bytes and then reassembling them the other way around, you can conceptually swap groups of bytes, like this: (not tested)

    public uint SwapBytes(uint x)
    {
        // swap adjacent 16-bit blocks
        x = (x >> 16) | (x << 16);
        // swap adjacent 8-bit blocks
        return ((x & 0xFF00FF00) >> 8) | ((x & 0x00FF00FF) << 8);
    }
    

    Doesn't help much (or at all) for 32 bits, but for 64 bits it does (not tested)

    public ulong SwapBytes(ulong x)
    {
        // swap adjacent 32-bit blocks
        x = (x >> 32) | (x << 32);
        // swap adjacent 16-bit blocks
        x = ((x & 0xFFFF0000FFFF0000) >> 16) | ((x & 0x0000FFFF0000FFFF) << 16);
        // swap adjacent 8-bit blocks
        return ((x & 0xFF00FF00FF00FF00) >> 8) | ((x & 0x00FF00FF00FF00FF) << 8);
    }
    

    For signed types, just cast to unsigned, do this, then cast back.

提交回复
热议问题