【问题标题】:Replacing bits in a Byte Array C#替换字节数组 C# 中的位
【发布时间】:2017-01-31 19:09:49
【问题描述】:

我想在 C# 中以字节数组的形式打开位图文件,并替换该数组中的某些字节,然后将字节数组作为位图重新写入磁盘。

我目前的方法是读入一个 byte[] 数组,然后将该数组转换为一个列表以开始编辑单个字节。

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

如何每次用用户配置/不同的字节替换数组中的每个第 n 个字节并重写回文件?

【问题讨论】:

  • 您知道您使用的是byte,它与bit 不同吗?请澄清您的问题。
  • 为错误道歉,已经澄清。我想替换数组中的字节,例如用 ASCII 字节字符替换一个字节(速记)。

标签: c# arrays bitmap byte


【解决方案1】:

List&lt;byte&gt;不需要

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

【讨论】:

  • 同意。打败我。
  • 如果我想每次都改变字节怎么办?
  • i 增加n 会加快速度
  • @ThomasD。是的,你是对的。这可能是一个更好的做法。
  • @Anton8000 每次什么?根据需要多次运行代码。但是考虑将i 增加n 作为@ThomasD。写如果性能很重要
【解决方案2】:

假设您想用相同的新字节替换每个第 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());

当然,你也可以用一个花哨的 LINQ 表达式来做到这一点,我猜它会更难阅读。

【讨论】:

    【解决方案3】:

    从技术上讲,你可以实现这样的东西:

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

    请注意,位图文件有一个标题

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

    这就是为什么我从n而不是0开始循环

    【讨论】:

      猜你喜欢
      • 2019-03-15
      • 1970-01-01
      • 2011-07-05
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 2016-09-10
      • 2012-09-20
      • 1970-01-01
      相关资源
      最近更新 更多