如何在.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 Framework(MSDN)中的字符编码。

其他回答

您需要考虑编码,因为1个字符可以由1个或多个字节(最多约6个)表示,不同的编码将对这些字节进行不同的处理。

Joel对此发表了一篇帖子:

绝对最低限度每个软件开发人员绝对、肯定地必须了解Unicode和字符集(没有借口!)

公认的答案非常非常复杂。为此,请使用包含的.NET类:

const string data = "A string with international characters: Norwegian: ÆØÅæøå, Chinese: 喂 谢谢";
var bytes = System.Text.Encoding.UTF8.GetBytes(data);
var decoded = System.Text.Encoding.UTF8.GetString(bytes);

如果你不需要。。。

Use:

    string text = "string";
    byte[] array = System.Text.Encoding.UTF8.GetBytes(text);

结果是:

[0] = 115
[1] = 116
[2] = 114
[3] = 105
[4] = 110
[5] = 103

只需使用此选项:

byte[] myByte= System.Text.ASCIIEncoding.Default.GetBytes(myString);

可以使用以下代码将字符串转换为.NET中的字节数组

string s_unicode = "abcéabc";
byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes(s_unicode);