Base-64 encodes the supplied block of data. - CSharp System

CSharp examples for System:String Base64

Description

Base-64 encodes the supplied block of data.

Demo Code

// This library is free software; you can redistribute it and/or
using System.Text;
using System;//w  w  w. j  a  va 2 s  .co m

public class Main{
    private static readonly string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    /// <summary>Base-64 encodes the supplied block of data.</summary>
      /// <remarks>
      /// Base-64 encodes the supplied block of data.  Line wrapping is not
      /// applied on output.
      /// </remarks>
      /// <param name="bytes">The block of data that is to be Base-64 encoded.</param>
      /// <returns>A <code>String</code> containing the encoded data.</returns>
      public static string Encode(byte[] bytes)
      {
         int length = bytes.Length;
         if (length == 0)
         {
            return string.Empty;
         }
         StringBuilder buffer = new StringBuilder((int)Math.Ceiling(length / 3d) * 4);
         int remainder = length % 3;
         length -= remainder;
         int block;
         int i = 0;
         while (i < length)
         {
            block = ((bytes[i++] & unchecked(0xff)) << 16) | ((bytes[i++] & unchecked(
               0xff)) << 8) | (bytes[i++] & unchecked(0xff));
            buffer.Append(Alphabet[(int)(((uint)block) >> 18)]);
            buffer.Append(Alphabet[((int)(((uint)block) >> 12)) & unchecked(0x3f)]);
            buffer.Append(Alphabet[((int)(((uint)block) >> 6)) & unchecked(0x3f)]);
            buffer.Append(Alphabet[block & unchecked(0x3f)]);
         }
         if (remainder == 0)
         {
            return buffer.ToString();
         }
         if (remainder == 1)
         {
            block = (bytes[i] & unchecked(0xff)) << 4;
            buffer.Append(Alphabet[(int)(((uint)block) >> 6)]);
            buffer.Append(Alphabet[block & unchecked(0x3f)]);
            buffer.Append("==");
            return buffer.ToString();
         }
         block = (((bytes[i++] & unchecked(0xff)) << 8) | ((bytes[i]) & unchecked(0xff))) << 2;
         buffer.Append(Alphabet[(int)(((uint)block) >> 12)]);
         buffer.Append(Alphabet[((int)(((uint)block) >> 6)) & unchecked(0x3f)]);
         buffer.Append(Alphabet[block & unchecked(0x3f)]);
         buffer.Append("=");
         return buffer.ToString();
      }
}

Related Tutorials