In C#, Convert.ToBase64CharArray encodes bytes into a char[] you allocate ahead of time.
It returns the number of characters written. Prefer ToBase64String when a simple string is enough.
This is a static member of System.Convert. You call it with the type name, such as Convert.ToBase64CharArray(...). Convert is the everyday API for converting between common CLR types in C#.
Syntax
Pass input bytes and an output char buffer with offsets.
C#
byte[] data = { 1, 2, 3 };
char[] buf = new char[8];
int written = Convert.ToBase64CharArray(data, 0, data.Length, buf, 0);
Call
What it does
Convert.ToBase64CharArray(data, 0, len, buf, 0)
Encode into buf starting at index 0.
Buffer must be large enough or ArgumentException is thrown. written tells you the used length.
Library declarations
C#
public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length,
char[] outArray, int offsetOut);
Parameters
Parameter
Description
inArray
Required. Source bytes.
offsetIn / length
Byte slice to encode.
outArray / offsetOut
Destination char buffer and start index.
Return Value
Return Value
Description
int
Number of Base64 characters written.
C# Examples
Example 1 — Encode into char[]
Fill a char buffer and print the written slice.
C#
using System;
class Program {
static void Main() {
byte[] data = { 1, 2, 3 };
char[] buf = new char[8];
int n = Convert.ToBase64CharArray(data, 0, data.Length, buf, 0);
Console.WriteLine(n);
Console.WriteLine(new string(buf, 0, n));
}
}
Output
4
AQID
How It Works
Allocate buf. Eight chars is plenty for three bytes.
written = 4. AQID needs four characters.
new string. Build text from only the used slice.
Same payload. Matches ToBase64String for {1,2,3}.
Example 2 — Write After a Prefix
Leave room at the start of the buffer.
C#
using System;
class Program {
static void Main() {
byte[] data = { 1, 2, 3 };
char[] buf = new char[10];
buf[0] = '#';
int n = Convert.ToBase64CharArray(data, 0, data.Length, buf, 1);
Console.WriteLine(n);
Console.WriteLine(new string(buf, 0, n + 1));
}
}
Output
4
#AQID
How It Works
Prefix char. Index 0 holds '#'.
offsetOut 1. Base64 starts at index 1.
written 4. Same encoded length.
Combined print. Shows #AQID together.
Example 3 — Encode Two Bytes Only
Limit length so only a prefix is encoded.
C#
using System;
class Program {
static void Main() {
byte[] data = { 1, 2, 3, 4 };
char[] buf = new char[8];
int n = Convert.ToBase64CharArray(data, 0, 2, buf, 0);
Console.WriteLine(new string(buf, 0, n));
Console.WriteLine(n);
}
}
Output
AQI=
2
How It Works
length 2. Only bytes 1 and 2 are encoded.
AQI=. Short Base64 with padding.
written count. Second line shows how many chars.
Ignore tail. Bytes 3 and 4 stay out of the encoding.
Frequently Asked Questions
To reuse buffers or write into an existing character workspace.