本文介绍了如何获得在C#中的字符串一致的字节重新presentation无需手动指定编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 如何将字符串转换为字节[] 在.NET(C#),而无需手动指定特定的编码?How do I convert a string to a byte[] in .NET (C#) without manually specifying a specific encoding?我要加密字符串。我可以加密它无需转换,但我还是想知道为什么编码来这里打球。只要给我个字节是我说的。I'm going to encrypt the string. I can encrypt it without converting but I'd still like to know why encoding comes to play here. Just give me the bytes is what I say.此外,为什么要编码加以考虑?不能我只是得到什么字节字符串已经被存储在?为什么会出现在字符编码的依赖?Also, why should encoding be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?推荐答案像你所说,你的目标是,简单地说,来的得到了什么字节字符串已经被保存在的。结果(而且,当然,能够重新构造从字节串。)Contrary to the answers here, you DON'T need to worry about encoding if the bytes don't need to be interpreted!Like you mentioned, your goal is, simply, to "get what bytes the string has been stored in".(And, of course, to be able to re-construct the string from the bytes.)只是这样做,而不是: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);}只要你的程序(或其他程序),不要尝试的间preT 的字节不知何故,这显然你没有提到你打算做的,再有就是什么错误的这种方法!担心编码只是让你的生活没有真正的理由更复杂。As long as your program (or other programs) don't try to interpret the bytes somehow, which you obviously didn't mention you intend to do, then there is nothing wrong with this approach! Worrying about encodings just makes your life more complicated for no real reason.这将是连接codeD和DE codeD一样的,因为你的只看该字节的It will be encoded and decoded just the same, because you are just looking at the bytes.如果你使用一个特定的编码,但是,它会一直给你麻烦的编码/解码无效字符。If you used a specific encoding, though, it would've given you trouble with encoding/decoding invalid characters. 这篇关于如何获得在C#中的字符串一致的字节重新presentation无需手动指定编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-16 10:19