问题

如何在.NET(C#)中将 string 转换为 byte [] 而不用手动指定特定的编码?

我要加密字符串.我可以加密而不转换,但我仍然想知道为什么编码在这里发挥.只是给我的字节是我说的.

此外,为什么要考虑编码?我不能只是得到什么字节的字符串已存储在?为什么存在对字符编码的依赖?



解决方法

Contrary to the answers here, you DON'T need to worry about encoding if the bytes don't need to be interpreted!

正如您所提到的,您的目标是简单地,"获取字符串存储在什么字节".
(当然,要能够从字节重新构造字符串.)

For those goals, I honestly do not understand why people keep telling you that you need the encodings. You certainly do NOT need to worry about encodings for this.

只需这样做:

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

static string GetString(byte[] bytes)
{
    char[] chars = new char[bytes.Length / sizeof(char)];
    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
    return new string(chars);
}

只要你的程序(或其他程序)不试图以某种方式解释字节,你显然没有提到你打算做,然后有没有< / strong>这个方法错了!担心编码只会使你的生活更复杂,没有真正的原因.

Additional benefit to this approach:

It doesn't matter if the string contains invalid characters, because you can still get the data and reconstruct the original string anyway!

它将被编码和解码的一样,因为你是只看字节.

如果您使用了特定的编码,则会给您带来编码/解码无效字符的麻烦.




相关问题推荐