How do you convert a string to ascii to binary in C#?

后端 未结 5 1712
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 23:01

A while back (freshman year of high school) I asked a really good C++ programmer who was a junior to make a simple application to convert a string to binary. He gave me the

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 23:22

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

    which outputs:

    01010100011001010111001101110100011010010110111001100111
    

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

提交回复
热议问题