Anthony
Anthony

Reputation: 136

Replacing bits in a Byte Array C#

I want to open a Bitmap File in C# as an array of bytes, and replace certain bytes within that array, and rewrite the Byte array back to disk as a bitmap again.

My current approach is to read into a byte[] array, then convert that array to a list to begin editing individual bytes.

originalBytes = File.ReadAllBytes(path);
List<byte> listBytes = new List<Byte>(originalBytes);

How does one go about replacing every nth byte in the array with a user configured/different byte each time and rewriting back to file?

Upvotes: 0

Views: 1514

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Technically, you can implement something like this:

 // ReadAllBytes returns byte[] array, we have no need in List<byte>
 byte[] data = File.ReadAllBytes(path);

 // starting from 0 - int i = 0 - will ruin BMP header which we must spare 
 // if n is small, you may want to start from 2 * n, 3 * n etc. 
 // or from some fixed offset
 for (int i = n; i < data.Length; i += n)
   data[i] = yourValue;

 File.WriteAllBytes(path, data);

Please notice, that Bitmap file has a header

https://en.wikipedia.org/wiki/BMP_file_format

that's why I've started loop from n, not from 0

Upvotes: 1

Thomas D.
Thomas D.

Reputation: 1051

Assuming that you want to replace every nth byte with the same new byte, you could do something like this (shown for every 3rd byte):

int n = 3;
byte newValue = 0xFF;
for (int i = n; i < listBytes.Count; i += n)
{
  listBytes[i] = newValue;
}

File.WriteAllBytes(path, listBytes.ToArray());

Of course, you could also do this with a fancy LINQ expression which would be harder to read i guess.

Upvotes: 2

rum
rum

Reputation: 242

no need in List<byte>

replaces every n-th byte with customByte

var n = 5;
byte customByte = 0xFF;

var bytes = File.ReadAllBytes(path);

for (var i = 0; i < bytes.Length; i++)
{
    if (i%n == 0)
    {
        bytes[i] = customByte;
    }
}

File.WriteAllBytes(path, bytes);

Upvotes: 4

Related Questions