Byte[] 到 String 到 Byte[] -- 如何做到这一点?
忽略为什么有人想要这样做的原因......:)
我希望能够获取一些字节,将它们转换为字符串,然后返回到相同字节数组。长度和一切都一样。
我尝试使用 ASCIIEncoder 类(仅适用于文本文件)和 Unicode Encoder 类(目前仅适用于数组 1024*n 大。我认为这是因为每个字符的长度相等),但没有成功。
有什么简单的方法可以做到这一点吗?我想我应该编写自己的函数来做到这一点,是吧?
Ignore the reasons why someone would want to do this.... :)
I want to be able to take some bytes, covert them to a string, then later back to the same byte array. Same length and everything.
I've tried using the ASCIIEncoder class (works for only text files) and Unicode Encoder class (only works so far for arrays 1024*n big. I assume this is because of the equal length of each character) with no success.
Is there any easy way to do this? I assume I should probably write my own functions to do so huh?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 Base64 编码。但它并不节省空间。
Use Base64 encoding. It's not space-efficient though.
Base64 非常适合解决此类问题。
请注意,结果字符串(当然)会比原始数组大。
Base64 is great at problems like this.
Note that the resulting string will be larger (of course) than your original array.
如果您不介意将每个 8 位字节存储到 16 位字符所需的空间加倍,并且不需要字符串由可打印字符组成,则可以直接这样做:
您可以编写更复杂的代码将两个 8 位字节打包到每个 16 位 Unicode 字符中,但随后您必须处理奇数字节数组长度的特殊情况(这可以在最后一个字符中使用额外的哨兵字节来完成) 。
If you don't mind the doubling of space required to store each 8-bit byte into a 16-bit char, and you don't need the string to be composed of printable characters, you could do it the direct way:
You could write more elaborate code to pack two 8-bit bytes into each 16-bit Unicode char, but then you'd have to handle the special cases of odd byte array lengths (which could be done using an extra sentinel byte in the last character).
如果您知道字符串的编码(我猜它是 UTF8),那么只需使用编码类:
编码类可以在 System.Text 命名空间
Y中找到。
If you know the encoding of your string (I would guess it is UTF8) then simply use the encoding class:
Encoding class can be found in the System.Text namespace
Y.