Search code examples
c#bitarray

BitArray to zeros and ones


I have this segment of code ...

string rand = RandomString(16);
byte[] bytes = Encoding.ASCII.GetBytes(rand);
BitArray b = new BitArray(bytes);

The code converts string to Bitarray properly. Now I need to convert the BitArray to zeros and ones.
I need to manipulate with zeros and ones variables (i. e. not for representation perposes [without left zeros padding] ). Can anyone help me please ?


Solution

  • BitArray class is the ideal class to use in your case for bitwise operations. You probably do not want to convert BitArray to bool[] or any other type if you want to do boolean operations. It stores bool values efficiently (1 bit for each) and provides you the necessary methods to do bitwise operations.

    BitArray.And(BitArray other), BitArray.Or(BitArray other), BitArray.Xor(BitArray other) are for boolean operations and BitArray.Set(int index, bool value), BitArray.Get(int index) to work with individual values.

    EDIT

    You can manipulate values individually using any bitwise operations:

    bool xorValue = bool1 ^ bool2;
    bitArray.Set(index, xorValue);
    

    You can have a collection of BitArray's of course:

    BitArray[] arrays = new BitArray[2];
    ...
    arrays[0].And(arrays[1]); // And'ing two BitArray's