Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Char[] to a List<byte> (c#)

Tags:

c#

generics

How can I convert a Char[] (of any length) to a List ?

like image 737
TK. Avatar asked Nov 30 '22 07:11

TK.


2 Answers

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

like image 22
TK. Avatar answered Dec 05 '22 05:12

TK.


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).

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>.

See my article on Unicode for more about the text conversion side of things (and links to more articles).

like image 193
Jon Skeet Avatar answered Dec 05 '22 07:12

Jon Skeet