i'm new to programming and as a desperate student i'm trying to develop a base conversion calculator program which converts a positive integer number (Num) from a given base (sourceBase) to an alternative base (targetBase), where sourceBase and targetBase are integer values ranging between 2 and 10 inclusive. The program should only perform the conversion if the user enters a valid source base number, otherwise an appropriate alert message should be posted.
Loading
Stephen PoppPosted Oct 31, 2006, 1:40 PM
Shared Function FromBaseN(ByVal strNumber As String, ByVal intBase As Integer) As Integer method... Don't want to spoil ALL the fun! Finally: Public Function FromBaseToBase(ByVal strNumber As String, ByVal fromBase As Integer, ByVal toBase As Integer) As String Return ToBaseN(FromBaseN(strNumber, fromBase), toBase) End FunctionStephen PoppPosted Oct 31, 2006, 1:30 PM
public static string ToBaseN(int intNumber, int intBase) { string functionReturnValue = null; int intRemainder = 0; int intLeftOver = System.Math.Abs(intNumber); StringBuilder buff = new StringBuilder(); if (intBase < 1 || intBase > 62) { throw new ArgumentException("Invalid numeric base. The base must be > 1 and < 62.", intBase); } while ((intLeftOver > 0)) { // Get the digit ordnal for the digit in the new base intRemainder = intLeftOver % intBase; // Select the new Base Digit buff.Insert(0, CHARACTER_LIST.ToCharArray()(intRemainder)); // Keep working what is left over intLeftOver = intLeftOver / intBase; } return buff.ToString(); }Stephen PoppPosted Oct 31, 2006, 11:24 AM
Private Const CHARACTER_LIST As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Shared Function ToBaseN(ByVal intNumber As Integer, ByVal intBase As Integer) As String Dim intRemainder As Integer = 0 Dim intLeftOver As Integer = System.Math.Abs(intNumber) Dim buff As New StringBuilder() If intBase < 1 OrElse intBase > 62 Then Throw New ArgumentException("Invalid numeric base. The base must be > 1 and < 62.", intBase) End If While (intLeftOver > 0) ' Get the digit ordnal for the digit in the new base intRemainder = intLeftOver Mod intBase ' Select the new Base Digit buff.Insert(0, CHARACTER_LIST.ToCharArray()(intRemainder)) ' Keep working what is left over intLeftOver = intLeftOver \ intBase End While Return buff.ToString() End Function