Sunday, April 7, 2013

Sasa.Web.Url64 - URL-Safe Base64 Encoding

This is the thirteenth post in my ongoing series covering the abstractions in Sasa. Previous posts:

Base64 encodings are built into .NET, but the standard Base64 encoding is not safe to use in URLs. Sasa.Web.Url64 provides methods to convert to and from a URL-safe Base64 representation I refer to as Url64.

Sasa.Web.Url64.FromUrl64

Sasa.Web.Url64.FromUrl64 is a simple extension method on strings to convert a Url64-encoded string to a byte array:

byte[] data = BitConverter.GetBytes(int.MinValue);
Console.WriteLine(data.ToUrl64());

int i = BitConverter.ToInt32(data.FromUrl64());
Console.WriteLine(i);
// output:
// aaaaGa
// -2147483648

Sasa.Web.Url64.ToUrl64

Sasa.Web.Url64.FromUrl64 is a set of extension methods on byte arrays to convert raw bytes to a Url64-encoded string:

byte[] data = BitConverter.GetBytes(int.MinValue);
Console.WriteLine(data.ToUrl64());

int i = BitConverter.ToInt32(data.FromUrl64());
Console.WriteLine(i);
// output:
// aaaaGa
// -2147483648

No comments: