Base64 and hex encoding

suggest change

Binary data (such as image bytes, hashes, or encryption keys) often needs to be transmitted or stored in text-only formats (like JSON, XML, or URL query parameters). C# and .NET provide built-in methods in System.Convert and System.Buffers.Text for Base64 and Hexadecimal encoding and decoding.

Base64 Encoding and Decoding

Base64 converts arbitrary bytes into a string composed of 64 ASCII characters (A-Z, a-z, 0-9, +, /, with = padding).

Basic String and Byte Conversion

Use Convert.ToBase64String and Convert.FromBase64String:

using System;
using System.Text;

string originalText = "Hello, C# World!";
byte[] originalBytes = Encoding.UTF8.GetBytes(originalText);

// Encode bytes to Base64 string
string base64String = Convert.ToBase64String(originalBytes);
Console.WriteLine($"Base64: {base64String}"); // SGVsbG8sIEMjIFdvcmxkIQ==

// Decode Base64 string back to bytes
byte[] decodedBytes = Convert.FromBase64String(base64String);
string restoredText = Encoding.UTF8.GetString(decodedBytes);
Console.WriteLine($"Restored: {restoredText}"); // Hello, C# World!

URL-Safe Base64 (Base64Url)

Standard Base64 contains characters (+, /, and =) that are reserved or modified in URL query strings. .NET 9+ provides Base64Url in System.Buffers.Text (available for older targets via the Microsoft.Bcl.Memory package):

using System.Buffers.Text;
using System.Text;

byte[] data = Encoding.UTF8.GetBytes("user:admin?status=active");

// Encodes '+' as '-' and '/' as '_', omitting '=' padding
string urlSafe = Base64Url.EncodeToString(data);
Console.WriteLine($"Base64Url: {urlSafe}"); // dXNlcjphZG1pbj9zdGF0dXM9YWN0aXZl

byte[] restored = Base64Url.DecodeFromChars(urlSafe);
Console.WriteLine($"Decoded: {Encoding.UTF8.GetString(restored)}");

In earlier .NET versions, convert manually by replacing + with -, / with _, and trimming trailing = characters.

Hexadecimal (Hex) Encoding and Decoding

Hexadecimal encoding represents each byte as two hexadecimal characters (0-9, a-f).

Modern .NET (Convert.ToHexString / Convert.FromHexString)

Starting with .NET 5, Convert.ToHexString and Convert.FromHexString provide fast, optimized conversion:

using System;
using System.Security.Cryptography;
using System.Text;

byte[] inputBytes = Encoding.UTF8.GetBytes("SecretData");
byte[] hashBytes = SHA256.HashData(inputBytes);

// Encode byte array to uppercase hex string
string hexHash = Convert.ToHexString(hashBytes);
Console.WriteLine($"SHA256 Hex: {hexHash}");

// Decode hex string back into a byte array
byte[] parsedBytes = Convert.FromHexString(hexHash);
Console.WriteLine($"Matches original hash: {hashBytes.AsSpan().SequenceEqual(parsedBytes)}");

To output lowercase hex in .NET 9+, use Convert.ToHexStringLower(hashBytes) or call .ToLowerInvariant() on earlier versions.

Legacy Hex Formatting

In older .NET Framework applications where Convert.ToHexString is unavailable, use BitConverter or StringBuilder:

using System;
using System.Text;

byte[] data = { 0x1A, 0x2B, 0x3C, 0x4D };

// BitConverter produces "1A-2B-3C-4D"
string hexWithHyphens = BitConverter.ToString(data);
string cleanHex = hexWithHyphens.Replace("-", "");
Console.WriteLine(cleanHex); // 1A2B3C4D

// Manual StringBuilder formatting
var sb = new StringBuilder(data.Length * 2);
foreach (byte b in data)
{
    sb.Append(b.ToString("x2")); // Lowercase two-digit hex
}
Console.WriteLine(sb.ToString()); // 1a2b3c4d

High-Performance Zero-Allocation Encoding

When handling high-throughput web traffic, avoid heap allocations by formatting directly into Span<char> or Span<byte> buffers:

using System;
using System.Buffers.Text;

ReadOnlySpan<byte> source = [0xDE, 0xAD, 0xBE, 0xEF];
Span<char> destination = stackalloc char[8];

// Formats directly into the stack-allocated span without string allocation (.NET 9+)
if (Convert.TryToHexString(source, destination, out int charsWritten))
{
    Console.WriteLine($"Span Hex: {destination[..charsWritten]}"); // DEADBEEF
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents