在c#中使用位操作进行快速数组处理 [英] using bit manipulation for fast array processing in c#

查看:394
本文介绍了在c#中使用位操作进行快速数组处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了很长时间了解程序员如何利用C#数组中数据的快速二进制表示的优势,但我只是不明白。



例如我有2个阵列A和B用于存储0/1数据。在正常情况下,我们喜欢这样:



I spent long time understanding how programmers use the advantage of speedy binary representation of data in C# arrays but I just dont get it.

for example If I have 2 arrays A, and B to store 0/1 data. In normal situation we do like this :

bool flag=true;
 int[] A = new int[10] { 1, 0, 0, 0, 1, 1, 0, 1, 0, 0 };
 int[] B = new int[10] { 1, 1, 1, 0, 0, 1, 0, 1, 0, 0 };
 // For comparing the first 5 bits :
 for(int i=0;i<5;i++)
     if (A[i] != B[i])
     {
         flag = false;
         break;
     }
 // Accessing the i*th* positions is :
 A[7]=1;
int x=B[5];





如果我需要重复此代码数千次怎么办?甚至阵列都很大?直接的答案是将数据表示为位打包数组,并应用按位运算或位掩码......等等。



我的问题是如何切换到c#中的二进制世界?为了更准确的问题,如何使用二进制表示和位操作以非常有效的方式重写上面的代码?非常感谢使用演示代码的答案。



What if I need to repeat this code for thousands of times ? or even the arrays are very large ? the straight answer will be to represent the data as bit packed arrays and apply things like bitwise operations or bitmasking ... etc.

My question is how to switch to the binary world in c# ? for more accurate question, How to rewrite the code above in very efficient way using the binary representation and bit wise operations ? Answer with demo code will be much appreciated.

推荐答案

我会使用BitArray class [ ^ ]。


您的基本问题是如何切换到二进制文件C#中的世界!答案是,一旦你了解了布尔代数 [ ^ ]它就像一块蛋糕!深入了解它的所有数学,看到你的代码似乎你没有审查这些概念。



一旦理解了理论,休息就很容易了。在C#
Your fundamental question is how to switch to the binary world in C#! And the answer is once you know the theory of Boolean Algebra[^] it would be like a peiece of cake! Deep down its all mathematics, seeing your code it seems like you have not reviewed these concepts.

Once you understand the theory, rest is easy. Check CPallini solution for Bit Array implementation in C#

这篇关于在c#中使用位操作进行快速数组处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆