如何在 C# 中将字符串转换为 ascii 到二进制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/736533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:11:52  来源:igfitidea点击:

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

c#c++binary

提问by Kredns

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 following code sample:

不久前(高中一年级),我问一位非常优秀的 C++ 程序员,他是一名大三学生,他制作了一个简单的应用程序,将字符串转换为二进制。他给了我以下代码示例:

void ToBinary(char* str)
{
    char* tempstr;
    int k = 0;

    tempstr = new char[90];

    while (str[k] != '
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));
}
') { itoa((int)str[k], tempstr, 2); cout << "\n" << tempstr; k++; } delete[] tempstr; }

So I guess my question is how do I get an equivalent to the itoa function in C#? Or if there is not one how could I achieve the same effect?

所以我想我的问题是如何获得与 C# 中的 itoa 函数等效的函数?或者如果没有,我怎么能达到同样的效果?

采纳答案by Samuel

This is very easy to do with C#.

这很容易用 C# 做到。

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

回答by JP Alioto

Use an ASCIIEncodingclass and call GetBytespassing the string.

使用ASCIIEncoding类并调用GetBytes传递字符串。

回答by mqp

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

目前还不清楚你想要什么,但我认为你想要的是:

string[] binaryDigits = str.Select(c => Convert.ToString(c, 2));
foreach(string s in binaryDigits) Console.WriteLine(s);

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

这不是 C++ 代码所做的。为此,我建议:

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.");
            }
        }
    }
}

回答by Jarrod

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

谢谢,这太棒了!!我用它来编码查询字符串......

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

回答by Krythic

Here's an extension function:

这是一个扩展函数:

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

You can use it like:

你可以像这样使用它:

01010100011001010111001101110100011010010110111001100111

which outputs:

输出:

##代码##

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

如果您添加 'true' 作为参数,它将自动分隔每个二进制序列。