Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

2.11. Encoding Binary Data as Base64

Problem

You have a byte[], which could represent some binary information such as a bitmap. You need to encode this data into a string so that it can be sent over a binary-unfriendly transport such as email.

Solution

Using the static method Convert.ToBase64CharArray on the Convert class, a byte[] may be encoded to a char[] equivalent, and the char[] can then be converted to a string:

using System;

public static string Base64EncodeBytes(byte[] inputBytes) 
{
    // Each 3-byte sequence in inputBytes must be converted to a 4-byte 
    // sequence 
    long arrLength = (long)(4.0d * inputBytes.Length / 3.0d);
    if ((arrLength  % 4) != 0) 
    {
        // increment the array length to the next multiple of 4 
        //    if it is not already divisible by 4
        arrLength += 4 - (arrLength % 4);
    }

    char[] encodedCharArray = new char[arrLength];
    Convert.ToBase64CharArray(inputBytes, 0, inputBytes.Length, encodedCharArray, 0);

    return (new string(encodedCharArray));
}

Discussion

The Convert class makes encoding between a byte[] and a char[] and/or a string a simple matter. The ToBase64CharArray method fills the specified character array with converted bytes, and also returns an integer specifying the number of elements in the resulting byte[], which, in this recipe, is discarded. As you can see, the parameters for this method are quite flexible. It provides the ability to start and stop the conversion at any point in the input byte array and to add elements starting at any position in the resulting ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata