【问题标题】:How to reverse bytes in certain order in file in C#?如何在 C# 中以特定顺序反转文件中的字节?
【发布时间】:2018-09-15 00:23:00
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# arrays endianness


    【解决方案1】:

    你可以用一个简单的实用函数来反转它们:

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

    【讨论】:

    • 不需要助手,为什么不直接使用Array.Reverse(fileBytes,0,4)?它针对原始类型进行了优化,并将使用在 CLR 中实现的 InternalCall TrySzReverse
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    相关资源
    最近更新 更多