【问题标题】:Easy way to generate XOR checksum on a stream?在流上生成 XOR 校验和的简单方法?
【发布时间】:2013-01-30 01:45:58
【问题描述】:

在 C# 中,是否有一种简单的方法可以在 MemoryStream(二进制)上生成 XOR 校验和,不包括第一个和最后两个字节?

另外,扩展 BinaryWriter 并在编写 Stream 时更容易吗?

【问题讨论】:

    标签: c# design-patterns checksum xor


    【解决方案1】:

    您可以使用 LINQ 来获得答案:

    var checksum = memStream
        .GetBuffer() // Get the underlying byte array
        .Skip(1)     // Skip the first byte
        .Take(memStream.Length-3) // One for the beginning, two more for the end
        .Aggregate(0, (p,v) => p ^ v); // XOR the accumulated value and the next byte
    

    【讨论】:

      猜你喜欢
      • 2015-03-20
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多