c#在字节数组上应用64位XOR

时间:2018-05-09 09:14:27

标签: c# xor

我想应用64字节操作的两个字节数组。这是使用unsafe

的正确方法吗?

我在不使用unsafe的情况下尝试了以下方法。但我想要比这快一点

for (int i=0; i< oldBlock.Length;i++)
{
{
 oldblock[i] ^= (newblock[i]);
}

在XOR操作之下,错过最后一个字节,如下所示,每次代码XOR为8个字节。

如何做到这一点。

static void Main(string[] args)
        {


            byte[] a = new byte[10];
            byte[] b = new byte[10];
            Random r = new Random();
            r.NextBytes(a);
            a.CopyTo(b, 0);
            XOr64(a, b);
            foreach (byte c in a)
            {
                Console.WriteLine(c);
            }


            Console.ReadKey();



        }    

public static unsafe void XOr64(byte[] oldBlock, byte[] newblock)
                {
                    try
                    {
                        fixed (byte* byteA = oldBlock)
                        fixed (byte* byteB = newblock)
                        {
                            long* ppA = (long*)byteA;
                            long* ppB = (long*)byteB;

                            for (int p = 0; p < oldBlock.Length/8; p++)
                            {
                                *ppA ^= *ppB;

                                ppA++;
                                ppB++;
                            }
                        }
                    }
                    catch
                    {

                    }



                }

1 个答案:

答案 0 :(得分:2)

如果一次8字节的方面对您有效,并且您确定需要额外的性能,则可以将该方法扩展为单独覆盖剩余的字节 - 这将是最多7个字节:

public static unsafe void XOr64(byte[] oldBlock, byte[] newBlock)
{
    // First XOR as many 64-bit blocks as possible, for the sake of speed
    fixed (byte* byteA = oldBlock)
    fixed (byte* byteB = newBlock)
    {
        long* ppA = (long*) byteA;
        long* ppB = (long*) byteB;

        int chunks = oldBlock.Length / 8;
        for (int p = 0; p < chunks; p++)
        {
            *ppA ^= *ppB;

            ppA++;
            ppB++;
        }
    }

    // Now cover any remaining bytes one byte at a time. We've
    // already handled chunks * 8 bytes, so start there.
    for (int index = chunks * 8; index < oldBlock.Length; index++)
    {
        oldBlock[index] ^= newBlock[index];
    }
}