C# Encoding Convert(Encoding, Encoding, Byte[])

Description

Encoding Convert(Encoding, Encoding, Byte[]) Converts an entire byte array from one encoding to another.

Syntax

Encoding.Convert(Encoding, Encoding, Byte[]) has the following syntax.


public static byte[] Convert(
  Encoding srcEncoding,//from  ww  w  .  j  a  va  2 s . c o  m
  Encoding dstEncoding,
  byte[] bytes
)

Parameters

Encoding.Convert(Encoding, Encoding, Byte[]) has the following parameters.

  • srcEncoding - The encoding format of bytes.
  • dstEncoding - The target encoding format.
  • bytes - The bytes to convert.

Returns

Encoding.Convert(Encoding, Encoding, Byte[]) method returns

Example


using System;//from   ww w.  j  ava 2  s.  co  m
using System.Text;

class Example
{
   static void Main()
   {
      string unicodeString = "This string contains the unicode character Pi (\u03a0)";
      Encoding ascii = Encoding.ASCII;
      Encoding unicode = Encoding.Unicode;
      byte[] unicodeBytes = unicode.GetBytes(unicodeString);

      byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

      char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
      ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
      string asciiString = new string(asciiChars);

      Console.WriteLine(unicodeString);
      Console.WriteLine(asciiString);
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Text »




ASCIIEncoding
Encoding
EncodingInfo
StringBuilder
UnicodeEncoding
UTF8Encoding