views:

1677

answers:

4

I have a list. I want to convert it to a byte[]. How do i do this? .toarray() creates a bool[].

+7  A: 

Here's two approaches, depending on whether you want to pack the bits into bytes, or have as many bytes as original bits:

    bool[] bools = { true, false, true, false, false, true, false, true,
                     true };

    // basic - same count
    byte[] arr1 = Array.ConvertAll(bools, b => b ? (byte)1 : (byte)0);

    // pack (in this case, using the first bool as the lsb - if you want
    // the first bool as the msb, reverse things ;-p)
    int bytes = bools.Length / 8;
    if ((bools.Length % 8) != 0) bytes++;
    byte[] arr2 = new byte[bytes];
    int bitIndex = 0, byteIndex = 0;
    for (int i = 0; i < bools.Length; i++)
    {
        if (bools[i])
        {
            arr2[byteIndex] |= (byte)(((byte)1) << bitIndex);
        }
        bitIndex++;
        if (bitIndex == 8)
        {
            bitIndex = 0;
            byteIndex++;
        }
    }
Marc Gravell
A: 

If you have any control over the type of list, try to make it a List, which will then produce the byte[] on ToArray(). If you have an ArrayList, you can use:

(byte[])list.ToArray(typeof(byte));

To get the List, you could create one with your unspecified list iterator as an input to the constructor, and then produce the ToArray()? Or copy each item, casting to a new byte from bool?

Some info on what type of list it is might help.

Richard Watson
False (-1) returns 255 for a signed byte.
Shimmy
A: 

Have a look at the BitConverter class. Depending on the exact nature of your requirement, it may solve your problem quite neatly.

dommer
+1  A: 

You can use LINQ. This won't be efficient, but will be simple. I'm assuming that you want one byte per bool.

bool[] a = new bool[] { true, false, true, true, false, true };
byte[] b = (from x in a select x ? (byte)0x1 : (byte)0x0).ToArray();
hfcs101
I wouldn't bet on this being particularly inefficient, until the input array starts having thousands of entries.
Richard