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

后端 未结 5 1701
佛祖请我去吃肉
佛祖请我去吃肉 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: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.");
                }
            }
        }
    }
    

提交回复
热议问题