Convert string of binary values to byte array

I have a string with binary values
(i.e. 0000000011001010111111110011111100111001101110001011011100110110001101011011010000110011101100101011000100111001101110001011011100110110001101011011010000110011101100101011000100111001101110001011011100110110001101011011010000110011101100101011000110111011111111110000000000000000000000000000000000000000000000000000000000000000)
that I need to convert to a unicode byte array.  

hess_joelAsked:
Who is Participating?
 
Bob LearnedConnect With a Mentor Commented:
Try this:
        public byte[] GetBytesFromBinaryString(string binary, int bitsPerByte)
        {
            List<byte> list = new List<byte>();
            for (int i = 0; i < binary.Length; i += bitsPerByte)
            {
                string t = binary.Substring(i, bitsPerByte);
 
                list.Add(Convert.ToByte(t, 2));
            }
            return list.ToArray();
        }

Open in new window

0
 
Bob LearnedCommented:
Do you need for each bit to be a byte in the array?

Bob
0
 
Bob LearnedCommented:
If you do, then try this:
            string s = "0000000011001010111111110011111100111001101110001011011100110110001101011011010000110011101100101011000100111001101110001011011100110110001101011011010000110011101100101011000100111001101110001011011100110110001101011011010000110011101100101011000110111011111111110000000000000000000000000000000000000000000000000000000000000000";
            List<byte> list = new List<byte>();
            foreach (char ch in s.ToCharArray())
            {
                list.Add((byte)((int)ch - 48));
            }
 
            byte[] byteArray = list.ToArray();

Open in new window

0
 
hess_joelAuthor Commented:
No, it's 8 bits per byte.
0
 
Bob LearnedCommented:
using System;
using System.Collections.Generic;

Bob

0
All Courses

From novice to tech pro — start learning today.