在 .NET 中如何将字符串转换为字节数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/241405/
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 you convert a string to a byte array in .NET?
提问by JonStonecash
I have a string that I need to convert to the equivalent array of bytes in .NET.
我有一个字符串,需要将其转换为 .NET 中的等效字节数组。
This ought to be easy, but I am having a brain cramp.
这应该很容易,但我脑抽筋了。
回答by Konrad Rudolph
You need to use an encoding(System.Text.Encoding) to tell .NET what you expect as the output. For example, in UTF-16 (= System.Text.Encoding.Unicode):
您需要使用编码( System.Text.Encoding) 来告诉 .NET 您期望什么作为输出。例如,在UTF-16 (= System.Text.Encoding.Unicode) 中:
var result = System.Text.Encoding.Unicode.GetBytes(text);
回答by Jon Skeet
First work out which encoding you want: you need to know a bit about Unicodefirst.
首先找出你想要的编码:你需要先了解一些关于 Unicode 的知识。
Next work out which System.Text.Encodingthat corresponds to. My Core .NET refcarddescribes most of the common ones, and how to get an instance (e.g. by a static property of Encodingor by calling a Encoding.GetEncoding.
接下来找出System.Text.Encoding对应的那个。我的Core .NET refcard描述了大多数常见的,以及如何获取实例(例如通过静态属性Encoding或调用Encoding.GetEncoding.
Finally, work out whether you want all the bytes at once (which is the easiest way of working - call Encoding.GetBytes(string)once and you're done) or whether you need to break it into chunks - in which case you'll want to use Encoding.GetEncoderand then encode a bit at a time. The encoder takes care of keeping the state between calls, in case you need to break off half way through a character, for example.
最后,确定您是否需要一次获得所有字节(这是最简单的工作方式 - 调用Encoding.GetBytes(string)一次即可完成),或者是否需要将其分成块 - 在这种情况下我想使用Encoding.GetEncoder然后一次编码一点。例如,编码器负责保持调用之间的状态,以防您需要在字符中途中断。
回答by swilliams
What Encoding are you using? Konrad's got it pretty much down, but there are others out there and you could get goofy results with the wrong one:
你使用什么编码?康拉德已经把它搞定了,但还有其他的,你可能会得到错误的结果:
byte[] bytes = System.Text.Encoding.XXX.GetBytes(text)
Where XXXcan be:
哪里XXX可以:
ASCII
BigEndianUnicode
Default
Unicode
UTF32
UTF7
UTF8
回答by Igal Tabachnik
Like this:
像这样:
string test = "text";
byte[] arr = Encoding.UTF8.GetBytes(test);

