Convert BitArray to byte[]

A question for those that, for one reason or another, have ever had to deal with binary on a Commercial Project.

Converting a Byte into its Binary representation is done as follows:

BitArray Name = new BitArray(byteobject);

The BitArray can then be indexed to work with the data and process it. However when trying to put the data BACK INTO THE FILE, a problem arises.

  1. BinaryWriter Streams only accept bytes and other data to be written to the data stream;
  2. Converter Class DOES NOT have any method which accepts a BitArray;
  3. BitConverter Class also DOES NOT have any method which accepts a BitArray;

So, if one wanted to write binary data back into a file, HOW IN HEAVENS NAME WOULD YOU DO IT



Answer this question

Convert BitArray to byte[]

  • Laura Cavanagh

    shakalama,

    Thanks for your response, however it appears as if you are still using data types.

    Let me give an example:

    ....

    public void Whole()

    {

    BinaryReader BinIn = new BinaryReader(BaseFile); //Basefile Class Member is a Filestream

    BinaryWriter BinOut = new BinaryWriter(OutputFile); //OutputFile Class Member is
    //a Filestream

    BitArray Extracted;

    Extracted = new BitArray(BinIn.ReadByte());

    //Code here that Process the Individual Binary Bits in this byte using index
    //"Extracted[Index]".

    //Now how can the BitArray "Extracted" be dumped into the OutputFile (BinOut)

    }


  • Ignasio Dondo

    Do you really need to convert the whole byte array into a BitArray You might work more efficiently with the byte array and bitmasks to extract and manipulate information.

    I wrote a sample that convert BitArray to a byte[]. Depending on how large arrays you are working with this can be taking a while.

    byte[] BitArrayToByteArray(BitArray bits)
    {
    // Who knows, might change
    const int
    BITSPERBYTE = 8;

    // Get the size of bytes needed to store all bytes
    int
    bytesize = bits.Length / BITSPERBYTE;
    // Any bit left over another byte is necessary
    if
    (bits.Length % BITSPERBYTE > 0)
    {
    bytesize++;
    }

    // For the result
    byte[] bytes = new byte
    [bytesize];

    // Must init to good value, all zero bit byte has value zero
    // Lowest significant bit has a place value of 1, each position to
    // to the left doubles the value
    byte
    value = 0;
    byte
    significance = 1;

    // Remember where in the input/output arrays
    int
    bytepos = 0;
    int
    bitpos = 0;

    while
    (bitpos < bits.Length)
    {
    // If the bit is set add its value to the byte
    if (true
    == bits[bitpos])
    {
    value += significance;
    }
    bitpos++;
    if
    (0 == bitpos % BITSPERBYTE)
    {
    // A full byte has been processed, store it
    // increase output buffer index and reset work values
    bytes[bytepos] = value;
    bytepos++;
    value = 0;
    significance = 1;
    }
    else
    {
    // Another bit processed, next has doubled value
    significance *= 2;
    }
    }
    return
    bytes;
    }



  • Jelle vd Beek

    Andreas Johansson,

    Fantastic!. However I am very surprised that BitArrays do not already come with this capability!!!

    This makes me think that perhaps I am doing things the hard way.

    If you received data into a computer in Binary (discrete message defined in bits and stored in a file), and you then want to write a program that interrogates the activity (by looking at the binary) and sends back binary instructions, how would you do this

    The program MUST respond in Binary, and store it in a file. Maybe there is a better way

    Please take these restrictions as fore-granted since I cannot go through the problem in detail on a public forum.

    I know you mentioned Bit Masks but I am not exactly sure how you would use them to achieve what I am trying to do.

    Cheers All!.


  • Ragas

    I wrote another two methods, these will let you work with a byte array in a similar way as BitArray does. IsBitSet() will check a bit and SetBit will set/clear it.

    If you want to read some more about bitmasks.
    http://en.wikipedia.org/wiki/Bitmask

    const int BITSPERBYTE = 8;
    // This gives the same result as BitArray[bitpos] on an
    // array that was created with new BitArray(bytes)
    bool IsBitSet(byte[] bytes, int
    bitpos)
    {
       // Get position in byte array
       int
    bytepos = bitpos / BITSPERBYTE;

       // Create bitmask, the byte array is per byte and the
       // bitmask take this into consideration. Bit 10 in the
       // bit array is bit 2 on the second byte.
       byte
    mask = 1;
       byte shift = (byte
    )(bitpos % BITSPERBYTE);
       mask = (
    byte
    )(mask << shift);

       // "Bitwise and" with the mask will return the mask
       // if the bit is set or zero if it is not.
       return
    ((bytes[bytepos] & mask) != 0);
    }

    // Sets the bit if state is true, otherwise clears it
    static void SetBit(byte[] bytes, int bitpos, bool
    state)
    {
       // Check if there actually is something to do
       if
    (IsBitSet(bytes, bitpos) == state)
       {
          return
    ;
       }

       // get position in bytearray and bitmask
       int
    bytepos = bitpos / BITSPERBYTE;
       byte
    mask = 1;
       byte shift = (byte
    )(bitpos % BITSPERBYTE);
       mask = (
    byte
    )(mask << shift);

       if (true == state)
       {
          // bitwise or with mask
          bytes[bytepos] |= mask;
       }
       else
       {
          // bitwise and with inverted mask
          bytes[bytepos] &= (byte
    )~mask;
       }

    }



  • Drca

    hi,

    you say for comercial i don't see anything comercial in bitarray but if binarywriter just take byte you can convert the bitarray to byte array, but if you iterate through it you will find it has extra elments than you actual data something like this


    int[] n = {1,2,3,4,5,6};
    BitArray bt = new BitArray(n);
    byte[] b = new byte[bt.Count];
    bt.CopyTo(b,
    0);
    int i = 0;
    foreach (byte item in b)
    {
    Console.WriteLine("line number {0} : value = {1} ",i,item.ToString());
    i++;
    }


    hope this helps



  • Aswani Kumar T

    hi,

    i guess your life will be easier if you used binary for just saving but to manuplate data you data you need datatypes and save it as binary no problem

    did you try to use filestream class and to set it as source for your reader and writer streams something like this


    FileStream fs = new FileStream(@"path.extention", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    BinaryReader br = new BinaryReader(fs);
    BinaryWriter bw = new BinaryWriter(fs);


     

    if the file is embeded resources in you project you can use System.Reflection name space here its a part of code that i have


    System.Reflection.Assembly assmb;

     int[, ,] array = new int[4, 5, 3];

    assmb = this.GetType().Assembly;//or System.Reflection.Assembly.GetExecutingAssembly()
    Stream s = assmb.GetManifestResourceStream("MyNamespace.Myfile.bin");
    BinaryReader r = new BinaryReader(s);

    for (int i = 0; i < 4; i++)
    {
    for (int j = 0; j < 5; j++)
    {
    Array[i, j,
    0] = r.ReadByte();
    Array[i, j,
    1] = r.ReadInt32();
    Array[i, j,
    2] = r.ReadInt16();
    }
    }
    r.Close();
    s.Close();

     

    hope this helps



  • Convert BitArray to byte[]