Skip to content

Instantly share code, notes, and snippets.

@JoshuaCarroll
Last active December 10, 2020 01:21
Show Gist options
  • Save JoshuaCarroll/9105631 to your computer and use it in GitHub Desktop.
Save JoshuaCarroll/9105631 to your computer and use it in GitHub Desktop.
This console application shows how to convert Base 32 numbers to decimal.
// Huge thanks to my friend Ben Andrews for writing a version of this in Java. Rewriting it in C# was a
// walk in the park after your work.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Base32Convertor
{
class Program
{
static void Main(string[] args)
{
int intBase = 0;
Console.WriteLine("What is your base?");
String strBase = Console.ReadLine();
if (!int.TryParse(strBase, out intBase))
{
return;
}
Console.WriteLine("What is your number?");
string inputString = Console.ReadLine().ToUpper();
char[] word = inputString.ToCharArray();
double result = 0;
int digit_count = 0;
for (int i = word.Length - 1; i > -1; i--, digit_count++)
{
int coefficient = char_to_int(word[i]);
double base_mult = Math.Pow(intBase, digit_count);
result += (coefficient * base_mult);
}
Console.WriteLine("Result is " + result + ".");
Console.ReadLine();
}
public static int char_to_int(char c)
{
int intval = (int)c;
int ret = 0;
if ((intval >= 48) && (intval <= 57))
{
/* This is a number */
ret = (int)(intval - 48);
}
else if ((intval >= 65) && (intval <= 90))
{
/* This is a letter */
ret = (int)(intval - 55);
}
return ret;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment