简体   繁体   中英

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM