Convert To and from Base 64 Char Array in CSharp

Description

The following code shows how to convert To and from Base 64 Char Array.

Example


using System;/*from w  ww.j  a v  a 2  s . c  om*/

class Sample
{
    public static void Main()
    {
        byte[] byteArray1 = new byte[256];
        byte[] byteArray2 = new byte[256];
        char[] charArray = new char[352];
        int charArrayLength;

        for (int x = 0; x < byteArray1.Length; x++)
        {
            byteArray1[x] = (byte)x;
            Console.Write("{0:X2} ", byteArray1[x]);
        }
        charArrayLength = Convert.ToBase64CharArray(byteArray1, 0, byteArray1.Length,
                                       charArray, 0, Base64FormattingOptions.InsertLineBreaks);
        Console.Write(charArrayLength);

        Console.WriteLine(new String(charArray));


        byteArray2 = Convert.FromBase64CharArray(charArray, 0, charArrayLength);

        Console.WriteLine(ArraysAreEqual(byteArray1, byteArray2));
    }

    public static bool ArraysAreEqual(byte[] a1, byte[] a2)
    {
        if (a1.Length != a2.Length) return false;
        for (int i = 0; i < a1.Length; i++)
            if (a1[i] != a2[i]) return false;
        return true;
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var