反转 BitArray 顺序的最有效方法?
我一直想知道在 C# 中反转 BitArray 顺序的最有效方法是什么。需要明确的是,我不想通过调用 .Not() 来反转 Bitarray,我想反转数组中位的顺序。
干杯, 克里斯
I've been wondering what the most efficient way to reverse the order of a BitArray in C#. To be clear, I don't want to inverse the Bitarray by calling .Not(), I want to reverse the order of the bits in the array.
Cheers,
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这将是最好的方法
反转 MSB <->在 for 循环中使用 XOR 的任意长度的 LSB
This will be the best way
to reverse MSB <-> LSB of any length using XOR in the for loop
对于一个简短但低效的答案:
For a short but inefficient answer:
因为如果大小固定为 8 位,则只需从下面进行“表”查找就足够了 - 在处理纯
字节
时,查找可能是最快的方法。然而,BitSet 获取/设置数据的额外开销可能会抵消查找的好处。此外,还需要考虑初始构建成本和持久开销(但这些值可以编码为数组文字......恶心!)另一方面,如果数据仅 8 位(曾经),并且“性能很重要”,为什么要使用 BitArray? BitArray 始终可以用于出色的功能,例如“爆炸”为 Enumerable,而 C# 已经内置了不错的字节位操作。
假设更一般的情况,数据是 8 位对齐的......但长度不确定
这实际上比仅仅在位数组? 我不知道,但怀疑不是。我肯定会从“简单”方法开始——这只是一个概念验证,在基准测试中进行比较可能(或可能不)有趣。无论如何,首先要写清楚......而下面的不是它! (其中至少有一个错误 - 我归咎于额外的复杂性;-)
输出:
expr.Dump()
是一个 LINQPad 功能。Because the size if fixed at 8-bits just the "table" lookup from below is sufficient -- when dealing with a plain
byte
a look-up is likely the quickest way. The extra overhead of BitSet to get/set the data may, however, nullify the look-up benefit. Also the initial build cost and persistent overhead need to be considered (but the values could be coded into an array literal ... ick!)On the other hand, if the data is only 8 bit (ever), and "performance is important", why use a BitArray at all? A BitArray could always be used for the nice features, such as "exploding" to an Enumerable while C# already has decent byte bit manipulation built-in.
Assuming a more general case that the data is 8-bit aligned... but of some undetermined length
Is this actually better (faster, more efficient, etc) than just doing it "per item" in the BitArray? I have no idea but suspect not. I would definitely start with the "simple" methods -- this is here as just a proof-of-concept and may (or may not be) interesting to compare in a benchmark. Anyway, write for clarity first ... and the below is not it! (There is at least one bug in it -- I blame the extra complexity ;-)
Output:
The
expr.Dump()
is a LINQPad feature.改编了@TimLoyd 的答案,并将其转变为扩展以方便使用。
用法:
Adapted the answer from @TimLoyd and turned it into an extension for easier use.
Usage:
对于长数组和相对较少的用途,只需将其包装起来:
For a long array and relative few uses, just wrap it: