Skip to content

Instantly share code, notes, and snippets.

@davidruhmann
Last active June 26, 2020 10:34
Show Gist options
  • Save davidruhmann/98d51e413d1b6b0b2899 to your computer and use it in GitHub Desktop.
Save davidruhmann/98d51e413d1b6b0b2899 to your computer and use it in GitHub Desktop.
C# Numeric Base Conversion
// Copyright (c) 2015 David Ruhmann
using System;
using System.Collections.Generic;
using System.Text;
namespace ChartedCode
{
public static class NumberExtensions
{
public static string ToBase(this int value, int radix, string digits)
{
if (string.IsNullOrEmpty(digits))
{
throw new ArgumentNullException("digits", string.Format("Digits must contain character value representations"));
}
radix = Math.Abs(radix);
if (radix > digits.Length || radix < 2)
{
throw new ArgumentOutOfRangeException("radix", radix, string.Format("Radix has to be > 2 and < {0}", digits.Length));
}
string result = string.Empty;
int quotient = Math.Abs(value);
while (0 < quotient)
{
int temp = quotient % radix;
result = digits[temp] + result;
quotient /= radix;
}
return result;
}
}
public static class StringExtensions
{
public static int FromBase(this string text, int radix, string digits, bool forgive = false)
{
if (string.IsNullOrEmpty(digits))
{
throw new ArgumentNullException("digits", string.Format("Digits must contain character value representations"));
}
radix = Math.Abs(radix);
if (radix > digits.Length || radix < 2)
{
throw new ArgumentOutOfRangeException("radix", radix, string.Format("Radix has to be > 2 and < {0}", digits.Length));
}
// Convert to Base 10
int value = 0;
if (!string.IsNullOrEmpty(text))
{
for (int i = text.Length - 1; i >= 0; --i)
{
int temp = digits.IndexOf(text[i]) * (int)Math.Pow(radix, text.Length - (i + 1));
if (0 > temp && !forgive)
{
throw new IndexOutOfRangeException("Text contains characters not found in digits.");
}
value += temp;
}
}
return value;
}
public static string ToBase(this string text, int fromRadix, string fromDigits, int toRadix, string toDigits)
{
return text.FromBase(fromRadix, fromDigits).ToBase(toRadix, toDigits);
}
public static string ToBase(this string text, int from, int to, string digits)
{
return text.FromBase(from, digits).ToBase(to, digits);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment