Reputation: 2970
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)
Upvotes: 2
Views: 4358
Reputation: 2975
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);
Upvotes: 0
Reputation: 20585
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;
}
Upvotes: 1
Reputation: 28107
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
Upvotes: 1
Reputation: 4740
string array = "1010101";
byte[] sequence = array.Select(c => Convert.ToByte(c.ToString())).ToArray();
Or
byte[] bytes = Encoding.ASCII.GetBytes(array);
Upvotes: 3
Reputation: 109597
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.
Upvotes: 0
Reputation: 14432
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;
}
Upvotes: 0