Archive for October, 2013

Monday, October 21st, 2013

If you ever need to encode an integer into base64 AND you control both ends of the conversion (such as wanting to use an integer for your own URL shortener). Here is a method for how to how you can tweak base64 conversions to get rid of the trailing equal signs (padding) and leading zeros (this will make the resulting string smaller).

public static string IntToCustomBase64String(int i)
{
	// Get the bytes from the int (will be an array of 4 bytes) 
	byte[] b = BitConverter.GetBytes(i);

	// Remove any leading 0s from the byte array
	int idx = b.Length - 1;
	while (b[idx] == 0)
		idx--;

	// Construct smaller byte array to copy items into
	byte[] new_b = new byte[idx + 1];
	Array.Copy(b, new_b, idx + 1);

	// return the new array
	return
		Convert.ToBase64String(new_b)
		.Replace("/", "!") // Make the string url safe
		.TrimEnd('='); // trim the padding. We know the # of bytes, 
		               // and we control conversion so this is okay
}

public static int CustomBase64ToInt(string customBase64EncodedString)
{
	// Add back the padding
	string s = customBase64EncodedString;
	if (s.Length == 2 || s.Length == 6)
		s += "==";
	else if (s.Length == 3)
		s += "=";

	// Get the bytes
	byte[] b = Convert.FromBase64String(s.Replace("!", "/"));

	// We need to add back any zero's we stripped to make this a 4 byte array
	// so it is a valid integer format
	byte[] new_b = new byte[] {0, 0, 0, 0};
	Array.Copy(b, new_b, b.Length);
	return BitConverter.ToInt32(new_b, 0);
}

Similar amount of bit fiddling could be down with any .NET type as long as you understand the bit structure of the type, and how you are transforming it.