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

Category: System.Text, viewed: 327 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();
        }
    }
}
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Statistics

Locations of visitors to this page