Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string of bits to byte array

Tags:

c#

.net

parsing

I have a string representing bits, such as:

"0000101000010000"

I want to convert it to get an array of bytes such as:

{0x0A, 0x10}

The number of bytes is variable but there will always be padding to form 8 bits per byte (so 1010 becomes 000010101).

like image 753
Roast Avatar asked Jun 07 '10 13:06

Roast


People also ask

How do you convert a string to a byte?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument.

Can we convert string to byte array in C#?

The Encoding. GetBytes() method converts a string into a bytes array. The example below converts a string into a byte array in Ascii format and prints the converted bytes to the console.

Is a string a byte array?

Remember that a string is basically just a byte array For example, the following code iterates over every byte in a string and prints it out as both a string and as a byte.

How many bits is a byte array?

1 Byte = 8 bits and you have a byte arrray.


2 Answers

Use the builtin Convert.ToByte() and read in chunks of 8 chars without reinventing the thing..

Unless this is something that should teach you about bitwise operations.

Update:


Stealing from Adam (and overusing LINQ, probably. This might be too concise and a normal loop might be better, depending on your own (and your coworker's!) preferences):

public static byte[] GetBytes(string bitString) {
    return Enumerable.Range(0, bitString.Length/8).
        Select(pos => Convert.ToByte(
            bitString.Substring(pos*8, 8),
            2)
        ).ToArray();
}
like image 60
Benjamin Podszun Avatar answered Sep 22 '22 06:09

Benjamin Podszun


public static byte[] GetBytes(string bitString)
{
    byte[] output = new byte[bitString.Length / 8];

    for (int i = 0; i < output.Length; i++)
    {
        for (int b = 0; b <= 7; b++)
        {
            output[i] |= (byte)((bitString[i * 8 + b] == '1' ? 1 : 0) << (7 - b));
        }
    }

    return output;
}
like image 22
Adam Robinson Avatar answered Sep 22 '22 06:09

Adam Robinson