如何在 C# 中按特定顺序反转文件中的字节?

How to reverse bytes in certain order in file in C#?

我想知道如何在我的 C# 代码中按文件中的特定顺序反转字节?让我更具体一点,我有一个文件,我需要反转其中某些字节的顺序(endian-swap)。

例如,我可以将字节 00 00 00 01 转换为 01 00 00 00 或将 00 01 转换为 01 00,反之亦然。

有谁知道我如何在 C# 代码中实现这一点?我是 C# 的新手,我一直在自己尝试,但无济于事。可以的话请帮忙,谢谢

您可以使用像这样的简单实用函数来反转它们:

public void ReverseBytes(byte[] array, int startIndex, int count)
{
    var hold = new byte[count];
    for (int i=0; i<count; i++)
    {
        hold[i] = array[startIndex + count - i - 1];
    }
    for (int i=0; i<count; i++)
    {
        array[startIndex + i] = hold[i];
    }
}

这样使用:

byte[] fileBytes = File.ReadAllBytes(path);
ReverseBytes(fileBytes, 0, 4);  //reverse offset 0x00 through 0x03
ReverseBytes(fileBytes, 4, 4);  //reverse 0x04 through 0x07
ReverseBytes(fileBytes, 8, 4);  //reverse 0x08 through 0x0B
//etc....
File.WriteAllBytes(path, fileBytes);

根据您的要求,您也可以使用循环:

for (int i=0; i<16; i+=4)
    ReverseBytes(fileBytes, i, 4);