views:

3794

answers:

2

How can I convert a Char[] (of any length) to a list < byte> ?

+13  A: 

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

Jon Skeet
I missed the byte type requirement in my answer, since it was missing in the original question. Therefore, upvote for this answer ;)
OregonGhost
Is there a question Jon hasn't answered in depth in an article :) Just kidding I love them!
Goran
"Is there a question Jon hasn't answered in depth in an article?" Ooh... I don't think I've got an article answering *that* question. Must fix ;)
Jon Skeet
+3  A: 

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

TK