更快的方式交换字节序在C#与16位字 [英] Faster way to swap endianness in C# with 16 bit words

查看:381
本文介绍了更快的方式交换字节序在C#与16位字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一定是一个更快,更好的方式来交换的16位字字节那么这样的:

There's got to be a faster and better way to swap bytes of 16bit words then this.:

public static void Swap(byte[] data)
{
    for (int i = 0; i < data.Length; i += 2)
    {
        byte b = data[i];
        data[i] = data[i + 1];
        data[i + 1] = b;
    }
}



有没有人有一个想法?

Does anyone have an idea?

推荐答案

在我尝试申请Uberhacker奖,我提出以下几点。对于我的测试中,我使用的8,192字节的源阵列,并呼吁 SwapX2 10万次:

In my attempt to apply for the Uberhacker award, I submit the following. For my testing, I used a Source array of 8,192 bytes and called SwapX2 100,000 times:

public static unsafe void SwapX2(Byte[] source)  
{  
    fixed (Byte* pSource = &source[0])  
    {  
        Byte* bp = pSource;  
        Byte* bp_stop = bp + source.Length;  

        while (bp < bp_stop)  
        {
            *(UInt16*)bp = (UInt16)(*bp << 8 | *(bp + 1));  
            bp += 2;  
        }  
    }  
}



我的基准测试表明,该版本比原来的问题提交的代码快了1.8倍。

My benchmarking indicates that this version is over 1.8 times faster than the code submitted in the original question.

这篇关于更快的方式交换字节序在C#与16位字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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