How do I convert string into an array of byte values?

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

To convert string to byte array of ASCII values we use the ASCIIEncoding.GetBytes method. And the UnicodeEncoding.GetBytes method can be used to convert string to byte array of Unicode values.

using System;
using System.Text;

namespace Kodecsharp.Example.System
{
    public class StringToBytes
    {
        public static void Main(string[] args)
        {
            //
            // Converting ASCII string to byte array.
            //
            ASCIIEncoding encoding = new ASCIIEncoding();

            String text = "ABCDEFGHIJ";
            byte[] characters = new byte[encoding.GetByteCount(text)];
            characters = encoding.GetBytes(text);

            for (int i = 0; i < characters.Length; i++)
            {
                Console.Write(characters[i]);
                if (i < characters.Length - 1)
                {
                    Console.Write(", ");
                }
            }

            Console.WriteLine();
            Console.WriteLine("----------------------------------------");

            //
            // Converting Unicode string to byte array.
            //
            UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
            String unicodeText = "Pi: (\u03a0), Sigma: (\u03a3)";
            byte[] unicodeCharacters = 
                new byte[unicodeEncoding.GetByteCount(unicodeText)];
            unicodeCharacters = unicodeEncoding.GetBytes(unicodeText);
            for (int i = 0; i < unicodeCharacters.Length; i++)
            {
                Console.Write(unicodeCharacters[i]);
                if (i < unicodeCharacters.Length - 1)
                {
                    Console.Write(", ");
                }
            }

            Console.ReadLine();
        }
    }
}
Powered by Disqus