Convert byte[] to char[]

C#ArraysCharacter EncodingType Conversion

C# Problem Overview


How do I convert a byte array to a char array in C#?

C# Solutions


Solution 1 - C#

System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();

Substitute the right encoding above: e.g.

System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();

Solution 2 - C#

You must know the source encoding.

string someText = "The quick brown fox jumps over the lazy dog.";
byte[] bytes = Encoding.Unicode.GetBytes(someText);
char[] chars = Encoding.Unicode.GetChars(bytes);

Solution 3 - C#

byte[] a = new byte[50];

char [] cArray= System.Text.Encoding.ASCII.GetString(a).ToCharArray();

From the URL thedixon posted

http://bytes.com/topic/c-sharp/answers/250261-byte-char

You cannot ToCharArray the byte without converting it to a string first.

To quote Jon Skeet there

> There's no need for the copying here - > just use Encoding.GetChars. However, > there's no guarantee that ASCII is > going to be the appropriate encoding > to use.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsaikameshView Question on Stackoverflow
Solution 1 - C#spenderView Answer on Stackoverflow
Solution 2 - C#BrettView Answer on Stackoverflow
Solution 3 - C#Ranhiru Jude CoorayView Answer on Stackoverflow