[英]How do you convert a string to ascii to binary in C#?
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. 前一阵子(高中一年级)我问过一个非常优秀的C ++程序员,他是一个初级的,可以创建一个简单的应用程序来将字符串转换为二进制。 He gave me the following code sample: 他给了我以下代码示例:
void ToBinary(char* str)
{
char* tempstr;
int k = 0;
tempstr = new char[90];
while (str[k] != '\0')
{
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#? 所以我想我的问题是如何在C#中获得等效的itoa函数? Or if there is not one how could I achieve the same effect? 或者,如果没有,我怎么能达到同样的效果?
This is very easy to do with C#. 使用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));
}
使用ASCIIEncoding类并调用GetBytes传递字符串。
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. 这不是C ++代码的作用。 For that, I suggest: 为此,我建议:
string[] binaryDigits = str.Select(c => Convert.ToString(c, 2));
foreach(string s in binaryDigits) Console.WriteLine(s);
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.");
}
}
}
}
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. 如果添加'true'作为参数,它将自动分隔每个二进制序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.