String to Binary in C#

前端 未结 4 1370
时光说笑
时光说笑 2020-11-27 18:22

I have a function to convert string to hex as this,

public static string ConvertToHex(string asciiString)
{
    string hex = \"\";
    foreach (char c in asc         


        
4条回答
  •  庸人自扰
    2020-11-27 18:53

    Here's an extension function:

            public static string ToBinary(this string data, bool formatBits = false)
            {
                char[] buffer = new char[(((data.Length * 8) + (formatBits ? (data.Length - 1) : 0)))];
                int index = 0;
                for (int i = 0; i < data.Length; i++)
                {
                    string binary = Convert.ToString(data[i], 2).PadLeft(8, '0');
                    for (int j = 0; j < 8; j++)
                    {
                        buffer[index] = binary[j];
                        index++;
                    }
                    if (formatBits && i < (data.Length - 1))
                    {
                        buffer[index] = ' ';
                        index++;
                    }
                }
                return new string(buffer);
            }
    

    You can use it like:

    Console.WriteLine("Testing".ToBinary());
    

    and if you add 'true' as a parameter, it will automatically separate each binary sequence.

提交回复
热议问题