简体   繁体   中英

Better way to convert a binary format string(0 and 1) to byte[]?

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)

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

Or

byte[] bytes = Encoding.ASCII.GetBytes(array);

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

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM