Skip to content

Instantly share code, notes, and snippets.

@ChrisMcKee
Created January 4, 2013 13:45
Show Gist options
  • Save ChrisMcKee/4452697 to your computer and use it in GitHub Desktop.
Save ChrisMcKee/4452697 to your computer and use it in GitHub Desktop.
Base65 Encoding
namespace Utils
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Base65Encoding
{
private const string Characters = "0123456789AaBbCcDdEeFfGgHhIiJjKklLMmNnOoPpQqRrSsTtUuVvWwXxYyZz._-";
public static string Encode(byte[] inArray)
{
var sb = new StringBuilder();
foreach (string val in inArray.Select(b => IntToString(b, Characters)))
{
if (val.Length == 1)
sb.Append("0").Append(val);
else
sb.Append(val);
}
return sb.ToString();
}
public static byte[] Decode(string inString)
{
if (string.IsNullOrEmpty(inString))
throw new ArgumentNullException("inString");
if (inString.Length%2 != 0)
throw new ArgumentException("Invalid string length", "inString");
var bytes = new List<byte>();
for (int i = 0; i < inString.Length; i += 2)
{
char ch = inString[i];
char ch2 = inString[i + 1];
int index = Characters.IndexOf(ch);
int index2 = Characters.IndexOf(ch2);
if (index < 0 || index2 < 0)
throw new ArgumentException("Invalid character: " + ch);
int val = 0;
val += (index*Characters.Length) + index2;
bytes.Add((byte) val);
}
return bytes.ToArray();
}
public static string IntToString(int value, string baseChars)
{
int i = 32;
var buffer = new char[i];
int targetBase = baseChars.Length;
do
{
buffer[--i] = baseChars[value%targetBase];
value = value/targetBase;
} while (value > 0);
var result = new char[32 - i];
Array.Copy(buffer, i, result, 0, 32 - i);
return new string(result);
}
}
}
namespace Utils
{
public static class EncodingExtensions
{
public static string ToBase65(this byte[] inArray)
{
return Base65Encoding.Encode(inArray);
}
public static byte[] FromBase65(this string inString)
{
return Base65Encoding.Decode(inString);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment