C# 如何将字节数组转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9828601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a byte array to a string?
提问by Ian Lundberg
I have a byte that is an array of 30 bytes, but when I use BitConverter.ToStringit displays the hex string. The byte is
0x42007200650061006B0069006E00670041007700650073006F006D0065.
Which is in Unicode as well.
我有一个字节,它是一个 30 字节的数组,但是当我使用BitConverter.ToString 时,它会显示十六进制字符串。字节是
0x42007200650061006B0069006E00670041007700650073006F006D0065. 这也是Unicode。
It means B.r.e.a.k.i.n.g.A.w.e.s.o.m.e, but I am not sure how to get it to convert from hex to Unicode to ASCII.
这意味着 BreakingAwesome,但我不知道如何让它从十六进制转换为 Unicode 到 ASCII。
采纳答案by Oded
You can use one of the Encodingclasses - you will need to know what encoding these bytes are in though.
您可以使用其中一个Encoding类 - 但是您需要知道这些字节的编码方式。
string val = Encoding.UTF8.GetString(myByteArray);
The values you have displayed look like a Unicode encoding, so UTF8or Unicodelook like good bets.
您显示的值看起来像 Unicode 编码,因此UTF8或Unicode看起来不错。
回答by Jon Skeet
It looks like that's little-endian UTF-16, so you want Encoding.Unicode:
看起来这是小端 UTF-16,所以你想要Encoding.Unicode:
string text = Encoding.Unicode.GetString(bytes);
You shouldn't normally assumewhat the encoding is though - it should be something you know about the data. For other encodings, you'd obviously use different Encodinginstances, but Encodingis the right class for binary representations of text.
您通常不应该假设编码是什么 - 它应该是您对数据的了解。对于其他编码,您显然会使用不同的Encoding实例,但它Encoding是用于文本二进制表示的正确类。
EDIT: As noted in comments, you appear to be missing an "00" either from the startof your byte array (in which case you need Encoding.BigEndianUnicode) or from the end(in which case just Encoding.Unicodeis fine).
编辑:如评论中所述,您似乎从字节数组的开头(在这种情况下需要Encoding.BigEndianUnicode)或结尾(在这种情况下就Encoding.Unicode可以)缺少“00” 。
(When it comes to the other way round, however, taking arbitrary binary data and representing it as text, you should use hex or base64. That's not the case here, but you ought to be aware of it.)
(然而,反过来说,取任意二进制数据并将其表示为文本,您应该使用十六进制或 base64。这里不是这种情况,但您应该意识到这一点。)

