各种类型的按位字节顺序交换 [英] Bitwise endian swap for various types

查看:242
本文介绍了各种类型的按位字节顺序交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

借助各种资源,我在我的二进制阅读器类中编写了一些 SwapBytes 方法,这些方法在 ushort uint ulong ,都在原始C#中全部使用按位运算,而无需任何不安全代码。

With the help of various sources, I have written some SwapBytes methods in my binary reader class that swap endian in ushort, uint, and ulong, all using bitwise operations all in raw C# with no need for any unsafe code.

public ushort SwapBytes(ushort x)
{
    return (ushort)((ushort)((x & 0xff) << 8) | ((x >> 8) & 0xff));
}

public uint SwapBytes(uint x)
{
    return ((x & 0x000000ff) << 24) +
           ((x & 0x0000ff00) << 8) +
           ((x & 0x00ff0000) >> 8) +
           ((x & 0xff000000) >> 24);
}

public ulong SwapBytes(ulong value)
{
    ulong uvalue = value;
    ulong swapped =
         ((0x00000000000000FF) & (uvalue >> 56)
         | (0x000000000000FF00) & (uvalue >> 40)
         | (0x0000000000FF0000) & (uvalue >> 24)
         | (0x00000000FF000000) & (uvalue >> 8)
         | (0x000000FF00000000) & (uvalue << 8)
         | (0x0000FF0000000000) & (uvalue << 24)
         | (0x00FF000000000000) & (uvalue << 40)
         | (0xFF00000000000000) & (uvalue << 56));
    return swapped;
}

我将如何创建相同的方法,但要针对每个方法的签名版本这些类型,例如short,int和long,仅使用与上述相同的方法,并且可以对上述方法进行哪些改进?

How would i go about creating the same methods but for the signed versions of each of these types, such as short, int and long, Using only the same methods as above, and what improvements could be made to the methods above?

推荐答案

您可以从概念上交换字节组,而不是从概念上解构为分开的字节,然后以相反的方式重新组装它们,例如:(未测试)

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);
}

对于32位并没有多大帮助(或根本没有帮助),但是对于它确实有64位(未经测试)

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.

这篇关于各种类型的按位字节顺序交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆