Witam!
Potrzebuję napisać program, który będzie mógł dokonywać konwersji pomiędzy systemem dwójkowym, ósemkowym, dziesiętnym i heksadecymalnym. Postanowiłem, że do problemu podejdę w następujący sposób. Z dowolnego systemu liczbowego zawsze będę dokonywać konwersja na system dziesiątkowy i dopiero z niego jeśli zajdzie konieczność dalej przekonwertuję liczbę na jakiś inny. Oto mój kod do tej pory. Wszystko muszę wykonać w C. Komentarzami proszę się nie przejmować.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//{
char Characters[16] =
{'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F'};
int UserInput;
//}
int main(void)
{
GetUserInput();
ConvertFromDecimal(UserInput,2);
getchar();
return 0;
}
void GetUserInput(void)
{
printf("\nEnter the number: ");
scanf("%d", &UserInput);
}
int ConvertToDecimal(int DesiredBase)
{
int Counter;
int Temp;
}
void ConvertFromDecimal(int NumberToConvertFromDecimal,int DesiredBase) //Function used to convert decimal numbert to any base
{
//Variables initialization
int NumberAfterConversion[126];
int Counter;
//Reseting counter
Counter = 0;
//Conversion part. Unless number is zero, this funtion will convert decimal number to any base using
//this simple algorithm:
if (NumberToConvertFromDecimal != 0)
{
while (NumberToConvertFromDecimal != 0)
{
NumberAfterConversion[Counter] = NumberToConvertFromDecimal % DesiredBase;
NumberToConvertFromDecimal = NumberToConvertFromDecimal / DesiredBase;
++Counter;
}
--Counter;
printf("\nNumer after base conversion: ");
for( ; Counter >= 0 ; Counter--)
{
printf("%c", Characters[NumberAfterConversion[Counter]]);
}
printf("\n");
}
else
{
printf("\nNumer after base conversion: 0");
}
}
Znalazłem taki oto kod, który jest w Pascalu i robi dokładnie to o co mi chodzi. Jednak ze względu na to, że jestem świeży w C proszę was o pomoc w przystosowaniu tego na moje potrzeby. Najbardziej boję się użycia wskaźników ponieważ nie do końca ogarniam ten temat.
function DowolnyNaDec(Liczba : String ; Podst : Integer) : Cardinal ;
var
Dana : Integer ;
i : Integer ;
begin
Result := 0 ;
if (Liczba = '') or (Podst < 2) or (Podst > 35) then Exit ; // 1
for i := 1 to Length(Liczba) do
begin
if Liczba[i] in ['A'..'Z'] then Dana := Ord(Liczba[i]) - Ord('A') + 10 // 2
else Dana := StrToInt(Liczba[i]) ;
if Dana >= Podst then // 3
begin
Result := 0 ;
Exit ;
end ;
Result := Result + Dana * Trunc(Exp((Length(Liczba) - i) * Ln(Podst))) ; // 4
end ;
end ;