blue piranha
blue piranha

Reputation: 3874

Integer array to bitarray in c#

I have an integer array of massive length. E.g. {2, 3, 4, 2, 4, 2, 1, 4, ....}. I would like to convert this into an array of BitArrays in C#. That is, 010 011 100 010 100 010 001 100

So this can be changed into 3 BitArrays (bitarray of left most bit, bitarray of middle bit, bitarray of right most bit)

Problem here is that unlike bitset in java where you can directly store 0/1, bitarrays can only contain true/false. And since this array is extremely long, I do not want to use if/else, that is

for(int i=0; i<N; i++)
   if (bit is 0) then  // time consuming step
       leftMostbitArray[0] = false;
   else
       leftMostbitArray[0] = true;

Is there any workaround where I could get rid of this step? Or probably a different datastructure. I would not like to use BitVector32 because of its size limitation.

Thanks.

Upvotes: 0

Views: 416

Answers (1)

Michael Bray
Michael Bray

Reputation: 15265

Try this:

int[] a = new int[] { 2, 3, 4, 2, 4, 2, 1, 4 };
BitArray b0 = new BitArray(a.Select(v => (v & (1 << 0)) != 0).ToArray());
BitArray b1 = new BitArray(a.Select(v => (v & (1 << 1)) != 0).ToArray());
BitArray b2 = new BitArray(a.Select(v => (v & (1 << 2)) != 0).ToArray());

The b0 will have the "bit-position 0", or the right-most bit. Then, b1 and b2 will have the next bit to the left, the next bit to the left, and so forth. You could add more lines to get additional bits if needed - just keep adding one to the bit-shift parameter (1 << #).

Also I couldn't tell if you really cared about BitVector using true/false or not - there's no functional difference between this and storing 0/1. If you really need to store 0/1 and you don't care about wasting memory, then you could use this syntax instead:

int[] vb0 = a.Select(v => (v & (1 << 0)) != 0 ? 1 : 0).ToArray()
...etc... 

Upvotes: 1

Related Questions