在.NET(C#)中,如何将一个 "字符串 "转换为 "字节[]",而无需手动指定特定的编码?
我打算对字符串进行加密。我可以在不转换的情况下进行加密,但我还是想知道为什么编码会在这里发挥作用。
另外,为什么要考虑到编码问题?难道我不能简单地获得字符串被存储在哪些字节中吗?为什么对字符编码有依赖性?
这取决于你的字符串的编码(ASCII, UTF-8, ...)。
比如说。
byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);
byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);
一个小例子,为什么编码很重要。
string pi = "\u03a0";
byte[] ascii = System.Text.Encoding.ASCII.GetBytes (pi);
byte[] utf8 = System.Text.Encoding.UTF8.GetBytes (pi);
Console.WriteLine (ascii.Length); //Will print 1
Console.WriteLine (utf8.Length); //Will print 2
Console.WriteLine (System.Text.Encoding.ASCII.GetString (ascii)); //Will print '?'
ASCII根本不具备处理特殊字符的能力。
在内部,.NET框架使用UTF-16来表示字符串,所以如果你只是想获得.NET使用的准确字节,可以使用System.Text.Encoding.Unicode.GetBytes(...)
。
参见.NET框架中的字符编码(MSDN)以了解更多信息。
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(dBytes);