将 Char[] 转换为 list<byte> (c#)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/162303/
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
Convert Char[] to a list<byte> (c#)
提问by TK.
How can I convert a Char[] (of any length) to a list < byte> ?
如何将 Char[](任意长度)转换为列表 < byte> ?
采纳答案by Jon Skeet
First you need to understand that chars aren't bytes in .NET. To convert between chars (a textual type) and bytes (a binary type) you need to use an encoding (see System.Text.Encoding).
首先,您需要了解字符不是 .NET 中的字节。要在字符(文本类型)和字节(二进制类型)之间进行转换,您需要使用编码(请参阅 System.Text.Encoding)。
Encoding will let you convert between string/char[] and byte[]. Once you've got a byte array, there are various ways of converting that into a List<byte> - although you may not even need to, as byte[] implements IList<byte>.
编码将让您在字符串/字符[] 和字节[] 之间进行转换。一旦您获得了一个字节数组,就可以通过多种方式将其转换为 List<byte> - 尽管您甚至可能不需要这样做,因为 byte[] 实现了 IList<byte>。
See my article on Unicodefor more about the text conversion side of things (and links to more articles).
有关文本转换方面的更多信息(以及指向更多文章的链接),请参阅我关于 Unicode 的文章。
回答by TK.
I have managed to use the following to get the job done:
我设法使用以下方法来完成工作:
byte[] arr = new System.Text.UTF8Encoding( true ).GetBytes( str );
List<byte> byteList = new List<byte>( arr );
Thanks for your help
谢谢你的帮助