i have the next string array {10100100, 11010000, 01000001, 11011000, 00000000, 10111100}
how can i convert it to byte[].
i tried bitconverter and some encoding options it didnt work.
Any ideas?

Recommended Answers

All 5 Replies

public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

Enter n > 0 < 1000:
2
Filling up first array
Enter element 0 in range [0-255]: 144
Enter element 1 in range [0-255]: 192
Filling up second array
Enter element 0 in range [0-255]: 0
Enter element 1 in range [0-255]: 198
Filling up third array
Enter element 0 in range [0-255]: 245
Enter element 1 in range [0-255]: 2
10100100 11010000 01000001 11011000 00000000 10011000 System.Byte[]
System.Byte[]
System.Byte[]
System.Byte[]
System.Byte[]
System.Byte[]

it doesnt seem to work for me

string[] result =  MergeElements(bitArray);
            foreach (string str in result)
                Console.Write(str + " ");
           for (int i = 0; i < result.Length; i++)
           {
               Console.WriteLine(StrToByteArray(result[i]));
           }

is there is an easy way or i should write a conversion in a old fashion way

may be i didnt explained it good.
i have this tring containing bit representation of the numbers that i need
string[] str = { "10100100", "11010000", "01000001", "11011000", "00000000", "10111100" };

i need each element in this string to be converted to byte(decimal number) and store those 6 elements in byte[] in the same order just converted to decimal.

here this works perfect:

public static byte[] StrToByteArray(string[] str)
        {
            byte[] array = new byte[str.Length];
            for (int i = 0; i < str.Length; i++)
            {
                array[i] = (byte)((str[i][0] == '1' ? 128 : 0) +
                      (str[i][1] == '1' ? 64 : 0) +
                      (str[i][2] == '1' ? 32 : 0) +
                      (str[i][3] == '1' ? 16 : 0) +
                      (str[i][4] == '1' ? 8 : 0) +
                      (str[i][5] == '1' ? 4 : 0) +
                      (str[i][6] == '1' ? 2 : 0) +
                      (str[i][7] == '1' ? 1 : 0));
            }
            return array;
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.