Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing the order of bytes in a file

Tags:

c#

Hi I am trying to reverse the bytes of a file without loading the entire file into memory.So far I only managed to read the bytes of the file from the end to begining , but I am not sure if I am doing it corectly.This is what I have so far:

        FileStream fileStream = new FileStream("file.txt", FileMode.Open, FileAccess.ReadWrite);
        fileStream.Seek(1024, SeekOrigin.End);
        byte[] buffer = new byte[1024];
        int count;
        while (fileStream.Position != 0)
        {
            count = fileStream.Read(buffer, 0, 1024);

        }

Now how can I reverse the order of bytes of a file and save it with the reversed order?

like image 441
aleczandru Avatar asked Jan 01 '26 08:01

aleczandru


1 Answers

I think you are best off reading the file in blocks, starting from the last block, reading each block and writing those bytes in reverse order.

An example:

MemoryStream output = new MemoryStream();
FileStream fs = new FileStream("D:\\file.txt", FileMode.Open);
long pos = fs.Length;
fs.Seek(0, SeekOrigin.End);
byte[] buffer = new byte[blockSize];
int length = blockSize;
while(pos > 0) {

    length = (int)(pos < blockSize ? pos : blockSize);
    pos -= length;
    fs.Seek(pos, SeekOrigin.Begin);

    int read = fs.Read(buffer,0, length);
    byte[] reversed = buffer.Take(read).Reverse().ToArray();
    output.Write(reversed,0, read);

} 

To keep the example simple, it is assumed that the Stream is actually reading length bytes when requested to. FileStream does this - but in case of other Stream implementations they might not (network streams et. al.).

You could also use a memory mapped file for this, as suggested in another answer. I don't know the exact overhead for using memory mapped files in .NET, so if it is important to you, try to measure the two methods against each other, using the actual file size you need to process. The block by block method involves a lot of file seeks if the file is large and the buffer is small. On the other hand, there will be an overhead in setting up the memory-mapped file.

like image 91
driis Avatar answered Jan 03 '26 21:01

driis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!