简体   繁体   English

替换字节数组C#中的位

[英]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. 我想在C#中以字节数组的形式打开位图文件,并替换该数组中的某些字节,然后再次将Byte数组作为位图重写回磁盘。

My current approach is to read into a byte[] array, then convert that array to a list to begin editing individual bytes. 我当前的方法是读入byte []数组,然后将该数组转换为列表以开始编辑各个字节。

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? 如何将阵列中的每个第n个字节每次替换为用户配置的/不同的字节,然后重新写回文件?

no need in List<byte> 不需要在List<byte>

replaces every n-th byte with customByte customByte替换每个第n个字节

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): 假设您要用相同的新字节替换每个第n个字节,则可以执行以下操作(每个第3个字节显示):

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. 当然,您也可以使用花哨的LINQ表达式来做到这一点,我猜这很难理解。

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 https://zh.wikipedia.org/wiki/BMP_file_format

that's why I've started loop from n , not from 0 这就是为什么我从n开始而不是从0开始循环的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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