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

后端 未结 5 1695
佛祖请我去吃肉
佛祖请我去吃肉 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:18

    This is very easy to do with C#.

    var str = "Hello world";
    
    With LINQ
    foreach (string letter in str.Select(c => Convert.ToString(c, 2)))
    {
      Console.WriteLine(letter);
    }
    
    Pre-LINQ
    foreach (char letter in str.ToCharArray())
    {
      Console.WriteLine(Convert.ToString(letter, 2));
    }
    
    0 讨论(0)
  • 2020-12-03 23:21

    It's not clear precisely what you want, but here's what I think you want:

    return Convert.ToString(int.Parse(str), 2); // "5" --> "101"
    

    This isn't what the C++ code does. For that, I suggest:

    string[] binaryDigits = str.Select(c => Convert.ToString(c, 2));
    foreach(string s in binaryDigits) Console.WriteLine(s);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 23:25

    Thanks, this is great!! I've used it to encode query strings...

    protected void Page_Load(object sender, EventArgs e)
    {
        string page = "";
        int counter = 0;
        foreach (string s in Request.QueryString.AllKeys)
        {
            if (s != Request.QueryString.Keys[0])
            {
                page += s;
                page += "=" + BinaryCodec.encode(Request.QueryString[counter]);
            }
            else
            {
                page += Request.QueryString[0];
            }
            if (!page.Contains('?'))
            {
                page += "?";
            }
            else
            {
                page += "&";
            }
            counter++;
        }
        page = page.TrimEnd('?');
        page = page.TrimEnd('&');
        Response.Redirect(page);
    }
    
    public class BinaryCodec
    {
        public static string encode(string ascii)
        {
            if (ascii == null)
            {
                return null;
            }
            else
            {
                char[] arrChars = ascii.ToCharArray();
                string binary = "";
                string divider = ".";
                foreach (char ch in arrChars)
                {
                    binary += Convert.ToString(Convert.ToInt32(ch), 2) + divider;
                }
                return binary;
            }
        }
    
        public static string decode(string binary)
        {
            if (binary == null)
            {
                return null;
            }
            else
            {
                try
                {
                    string[] arrStrings = binary.Trim('.').Split('.');
                    string ascii = "";
                    foreach (string s in arrStrings)
                    {
                        ascii += Convert.ToChar(Convert.ToInt32(s, 2));
                    }
                    return ascii;
                }
                catch (FormatException)
                {
                    throw new FormatException("SECURITY ALERT! You cannot access a page by entering its URL.");
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-03 23:29

    Use an ASCIIEncoding class and call GetBytes passing the string.

    0 讨论(0)
提交回复
热议问题