Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert bitarray to string

Tags:

c#

Could someone help me to convert bittarray to string properly? I wrote this:

static String BitArrayToStr(BitArray ba)
        {
            byte[] strArr = new byte[ba.Length / 8];

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            for (int i = 0; i < ba.Length / 8; i++)
            {
                for (int index = i * 8, m = 1; index < i * 8 + 8; index++, m *= 2)
                {
                    strArr[i] += ba.Get(index) ? (byte)m : (byte)0;
                }
            }

            return encoding.GetString(strArr);
        }

but on the output I have this: "���*Ȱ&����L9��q�zȲP���*Ȱ&����L9��q�zȲP���*Ȱ&Y(W�" -many unrecognised symbols, what shoud I do?

like image 534
ZAA Avatar asked Oct 12 '10 16:10

ZAA


1 Answers

You can use this extension method:

public static string ToBitString(this BitArray bits)
{
    var sb = new StringBuilder();

    for (int i = 0; i < bits.Count; i++)
    {
        char c = bits[i] ? '1' : '0';
        sb.Append(c);
    }

    return sb.ToString();
}
like image 99
oleksii Avatar answered Sep 23 '22 11:09

oleksii