Roast
Roast

Reputation: 1755

How to convert a string of bits to byte array

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).

Upvotes: 8

Views: 28065

Answers (7)

Ritesh Khokhani
Ritesh Khokhani

Reputation: 59

You can go any of below,

        byte []bytes = System.Text.Encoding.UTF8.GetBytes("Hi");
        string str = System.Text.Encoding.UTF8.GetString(bytes);


        byte []bytesNew = System.Convert.FromBase64String ("Hello!");
        string strNew = System.Convert.ToBase64String(bytesNew);

Upvotes: -3

drayv
drayv

Reputation: 11

private static byte[] GetBytes(string bitString)
{
    byte[] result = Enumerable.Range(0, bitString.Length / 8).
        Select(pos => Convert.ToByte(
            bitString.Substring(pos * 8, 8),
            2)
        ).ToArray();

    List<byte> mahByteArray = new List<byte>();
    for (int i = result.Length - 1; i >= 0; i--)
    {
        mahByteArray.Add(result[i]);
    }

    return mahByteArray.ToArray();
}

private static String ToBitString(BitArray bits)
{
    var sb = new StringBuilder();

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

    return sb.ToString();
}

Upvotes: 0

VBK
VBK

Reputation: 91

Here's a quick and straightforward solution (and I think it will meet all your requirements): http://vbktech.wordpress.com/2011/07/08/c-net-converting-a-string-of-bits-to-a-byte-array/

Upvotes: 2

Benjamin Podszun
Benjamin Podszun

Reputation: 9837

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();
}

Upvotes: 10

Guffa
Guffa

Reputation: 700800

Get the characers in groups of eight, and parse to a byte:

string bits = "0000101000010000";

byte[] data =
  Regex.Matches(bits, ".{8}").Cast<Match>()
  .Select(m => Convert.ToByte(m.Groups[0].Value, 2))
  .ToArray();

Upvotes: 0

Adam Robinson
Adam Robinson

Reputation: 185703

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;
}

Upvotes: 2

Andrew Anderson
Andrew Anderson

Reputation: 3449

This should get you to your answer: How can I convert bits to bytes?

You could just convert your string into an array like that article has, and from there use the same logic to perform the conversion.

Upvotes: 0

Related Questions