CSharp - String and byte arrays encoding

Introduction

You can use an Encoding object to encode a byte array.

GetBytes method converts from string to byte[] with the given encoding.

GetString method converts from byte[] to string:

Demo

using System;
class MainClass//from   w  w w .j  a v  a  2  s  .c o m
{
   public static void Main(string[] args)
   {

     byte[] utf8Bytes  = System.Text.Encoding.UTF8.GetBytes    ("0123456789");
     byte[] utf16Bytes = System.Text.Encoding.Unicode.GetBytes ("book2s.com");
     byte[] utf32Bytes = System.Text.Encoding.UTF32.GetBytes   ("this is a test");

     Console.WriteLine (utf8Bytes.Length);    
     Console.WriteLine (utf16Bytes.Length);   
     Console.WriteLine (utf32Bytes.Length);   

     string original1 = System.Text.Encoding.UTF8.GetString    (utf8Bytes);
     string original2 = System.Text.Encoding.Unicode.GetString (utf16Bytes);
     string original3 = System.Text.Encoding.UTF32.GetString   (utf32Bytes);

     Console.WriteLine (original1);          
     Console.WriteLine (original2);          
     Console.WriteLine (original3);          
   }
}

Result