Csharp/CSharp Tutorial/I18N Internationalization/Encoding Based64

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Base64 encode a Unicode string as a string

<source lang="csharp">using System; using System.IO; using System.Text; class MainClass {

   public static void Main() 
   {
       byte[] b = Encoding.Unicode.GetBytes("string");
       // Return the Base64-encoded string.
       string str =  Convert.ToBase64String(b);
       Console.WriteLine(str);
       Convert.FromBase64String(str);
       // Return the decoded Unicode string.
       Console.WriteLine(Encoding.Unicode.GetString(b));
   }

}</source>

cwB0AHIAaQBuAGcA
string

Decode a Base64-encoded Unicode string from a string

<source lang="csharp">using System; using System.IO; using System.Text; class MainClass {

   public static void Main() 
   {
       byte[] b = Encoding.Unicode.GetBytes("string");
       // Return the Base64-encoded string.
       string str =  Convert.ToBase64String(b);
       Console.WriteLine(str);
       Convert.FromBase64String(str);
       // Return the decoded Unicode string.
       Console.WriteLine(Encoding.Unicode.GetString(b));
   }

}</source>

cwB0AHIAaQBuAGcA
string

Decode the Base64-encoded int to a byte array

<source lang="csharp">using System; using System.IO; using System.Text; class MainClass {

   public static void Main() 
   {
       // Get a byte representation of the int.
       byte[] b = BitConverter.GetBytes(123);
       // Return the Base64-encoded int.
       string str =  Convert.ToBase64String(b);
       Console.WriteLine(str);
       
       b = Convert.FromBase64String(str);
       // Return the decoded int.
       int i =  BitConverter.ToInt32(b,0);
       
       Console.WriteLine(i);
       
   }

}</source>

ewAAAA==
123

Encode int to the Base64-encoded byte array

<source lang="csharp">using System; using System.IO; using System.Text; class MainClass {

   public static void Main() 
   {
       // Get a byte representation of the int.
       byte[] b = BitConverter.GetBytes(123);
       // Return the Base64-encoded int.
       string str =  Convert.ToBase64String(b);
       Console.WriteLine(str);
       
       b = Convert.FromBase64String(str);
       // Return the decoded int.
       int i =  BitConverter.ToInt32(b,0);
       
       Console.WriteLine(i);
   }

}</source>

ewAAAA==
123