Search code examples
c#arraysendianness

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


I was wondering in my C# code how I can reverse bytes in a certain order in a file? Let me be more specific, I have a file and I need to reverse the order of some bytes inside of it (endian-swap).

So for example I could turn the bytes 00 00 00 01 into 01 00 00 00 or 00 01 into 01 00 and vice versa.

Does anyone know how I can achieve this in C# code? I am quite new to C# and I have been attempting this on my own however to no avail. Please help if you can, thank you.


Solution

  • You can reverse them with a simple utility function like this one:

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

    Use it like this:

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

    Depending on your requirements you may be able to use a loop too:

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