1

I have write this, is a good one?

byte[] ConvertToBytes(string b)
    {
        BitArray bits = new BitArray(b.ToList().ConvertAll<bool>(x => x == '1').ToArray());

        byte[] ret = new byte[bits.Length];
        bits.CopyTo(ret, 0);

        return ret;
    }

(the array must be readable as an ascii string)

Sam
  • 2,950
  • 1
  • 18
  • 26
  • Efficient wise ? I can write better. Also you're not checking for null string b (throwing ArgumentNullException ...) – Ondrej Svejdar Oct 31 '13 at 14:10
  • tnw, I put it in linqpad and the intellisense didn't pick up on it, but it compiled and ran! – HL-SDK Oct 31 '13 at 14:13
  • 2
    tnw, this actually work for me lol – Sam Oct 31 '13 at 14:13
  • @tnw http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx – MrDosu Oct 31 '13 at 14:14
  • possible duplicate of [Convert string representation of binary number to int in C#](http://stackoverflow.com/questions/14264203/convert-string-representation-of-binary-number-to-int-in-c-sharp) – John Alexiou Oct 31 '13 at 14:24
  • @Sam Are you set on using `byte[]`? Personally I prefer dealing with binary numbers as integers (see [my answer](http://stackoverflow.com/a/19709466/1185053)) – dav_i Oct 31 '13 at 15:07

6 Answers6

2
string array = "1010101";
byte[] sequence = array.Select(c => Convert.ToByte(c.ToString())).ToArray();

Or

byte[] bytes = Encoding.ASCII.GetBytes(array);
Lucas_Santos
  • 4,638
  • 17
  • 71
  • 118
1

Alternative:

You may be better off not using byte[] but actually just storing the binary number as an integer:

Convert.ToInt32("1011", 2) // returns 11

And the other way round:

Convert.ToString(11, 2) // returns "1011"

And if you need to get the nth bit across (from right):

public int GetNthBit(int binary, int n)
{
    return (binary >> n) % 2;
}

Usage:

GetNthBit(11, 2) // returns 0
dav_i
  • 27,509
  • 17
  • 104
  • 136
1

I can suggest a efficient way, thought it must not be that hard to implement.

I am assuming that the string will well formed that it is a binary representation in string format.

private static byte[] BinStringToBytes(string binary)
{
    //make sure the string length is multiple of 32, if not pad it with zeroes
    var neededZeros = 32 - (binary.Length % 32);

    if (neededZeros > 0)
        binary = string.Concat(new string('0', neededZeros), binary);

    var blocks = binary.Length / 32;

    var binbytes = new byte[blocks * 4];

    for (var i = 0; i < blocks; i++)
    {
        var numstr = binary.Substring(i * 32, 32);
        var num = Convert.ToUInt32(numstr, 2);
        var bytes = BitConverter.GetBytes(num);
        Array.Copy(bytes, 0, binbytes, i * 4, 4);
    }

    return binbytes;
}
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
  • A bit long and gives me a deformed string, for example `loool` in binary become `l looo` on decoding. I was searching for something like a direct decoding method, but there isn't so i continue to use my own, anyway thanks. – Sam Oct 31 '13 at 15:46
0

Mehrdad has a good answer to your question. The code:

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}
Community
  • 1
  • 1
Abbas
  • 14,186
  • 6
  • 41
  • 72
  • i get the same binary string just with a space between the numbers, like this `0 1 1 1 0 1 0 0 0 1 1 0 0 1 0 1 0 1 1 1 0 0 1 1 0 1 1 1 0 1 0 0` – Sam Oct 31 '13 at 14:18
0

It's possible I misunderstand the question, but:

public byte[] BitStringToAsciiArray(string bits)
{
    return Encoding.ASCII.GetBytes(bits);
}

However, it doesn't give any error if any of the characters in the input string are something other than '0' or '1'.

But otherwise it does return an array of bytes each which is 48 for a '0' in the input string and 49 for a '1' in the input string. These are the ASCII codes for '0' and '1' respectively.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • The function must convert the binary format to byte[], not just the string, else i get the same one decoding the bytes – Sam Oct 31 '13 at 14:37
  • @Sam What binary format? The input is a string. Can you provide a sample input string? From your question, one would assume that it would look like: "1010111010110" kind of thing. And if the output array must be readable as an ASCII string, it can consist only of bytes with the values 48 or 49. – Matthew Watson Oct 31 '13 at 15:03
0

Append all the chars into a long as below:

var l = 0L;
foreach (var c in s)
{
    l <<= 1;
    l += c;
}
var b = BitConverter.GetBytes(l);
pasx
  • 2,718
  • 1
  • 34
  • 26