n32303
n32303

Reputation: 829

Convert string of bits to byte[] c#

I know how to convert for example $ -> 00100100

        string input1 = input.Text;
        byte[] bitniTekst;
        bitniTekst = System.Text.Encoding.UTF8.GetBytes(input1);
        Array.Reverse(bitniTekst);
        BitArray biti = new BitArray(bitniTekst);

        string output = "";

        for (int i = biti.Length - 1; i >= 0; i--)
        {
            if (biti[i] == true)
            {
                output += "1";
            }
            else
            {
                output += "0";
            }
        }

But I don't know how to convert from a string of bits to a byte array, to use

System.Text.Encoding.UTF8.GetString(byte[]);

for example -> if user inputs 00100100 I want to get $ char.

Upvotes: 0

Views: 4426

Answers (1)

Guffa
Guffa

Reputation: 700342

Use the Convert class to parse the string as a binary (base 2) number. Example:

string s = "00100100";

byte[] bytes = new byte[1];

bytes[0] = Convert.ToByte(s, 2);

string result = Encoding.UTF8.GetString(bytes);

Upvotes: 4

Related Questions