How do I convert byte array into string?

Category: System.Text, viewed: 2K time(s).

In the following example you'll see how we convert a array of bytes of ASCII characters and UTF-16 characters into string. To get the string of this bytes we use the ASCIIEncoding and UnicodeEncoding classes which can be located in the System.Text namespace.

The ASCIIEncoding.GetString method converts 7-bit ASCII characters from the byte array into a string. Any value larger than 127 is converted to the ? character. And the UnicodeEncoding.GetString method converts 16-bit unicode characters from the byte array into a string.

using System;
using System.Text;

namespace Kodecsharp.Example.System
{
    public class BytesToString
    {
        public static void Main(string[] args)
        {
            //
            // byte array representing the ASCII characters from A to J
            //
            byte[] asciiCharacters = new byte[] {
                65, 66, 67, 68, 69,                                             
                70, 71, 72, 73, 74
            };

            //
            // Converting from byte[] of characters to ASCII
            //
            ASCIIEncoding asciiEncoding = new ASCIIEncoding();
            string text = asciiEncoding.GetString(asciiCharacters);
            Console.Out.WriteLine("Text = " + text);

            //
            // Converting from byte[] of characters to UTF-16
            //
            byte[] utf16Characters = new byte[] {
                65, 0, 66, 0, 67, 0, 68, 0, 69, 0,
                70, 0, 71, 0, 72, 0, 73, 0, 74, 0
            };

            UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
            text = unicodeEncoding.GetString(utf16Characters);
            Console.Out.WriteLine("Text = " + text);

            //
            // Converting string with unicode characters.
            //
            String utf16Text = "Pi: (\u03a0), Sigma: (\u03a3)";
            utf16Characters = unicodeEncoding.GetBytes(utf16Text);
            text = unicodeEncoding.GetString(utf16Characters);
            Console.Out.WriteLine("Text = " + text);
            
            Console.ReadLine();
        }
    }
}
Powered by Disqus