I'm trying to make a program that converts decimal to binary, octal and hexadecimal. My intention is to make a program that can convert "any" number, regardless of its size for these other bases.
My doubt in the case is: from decimal 1.10¹⁵ the program does not properly convert the value, why does this happen? In fact, if someone knows a better way to do it, and certainly has one, and can pass me, I would appreciate it.
#include <stdio.h>
#include <math.h>
int b=0,o=0,h;
void ConvertToBinary(long double n);
void ConvertToOctal(long double n);
void ConvertToHexa( long double n);
int main() {
long double x=0;
printf("Valor na base Decimal:");
scanf("%Lg",&x);
printf("Em Binario: ");
ConvertToBinary(x);
printf("\nEm Octadecimal: ");
ConvertToOctal(x);
printf("\nEm Hexadecimal: ");
ConvertToHexa(x);
printf("\n");
return 0;
}
void ConvertToBinary(long double n)
{
int i=0;
if(n == 0){
printf("0");
}
else{
if ( n / 2 != 0) {
ConvertToBinary( n / 2);
}
if( b==0){
if( ((int) n%2) == 1){
++i;
}
}
b = b+i;
if(b >= 1){
printf("%d", (int) n % 2);
}
}
}
void ConvertToOctal(long double n)
{
int i=0;
if(n == 0){
printf("0");
}
else{
if ( n / 8 != 0) {
ConvertToOctal( n / 8);
}
if( o==0){
if( ((int) n%8) != 0){
++i;
}
}
o = o+i;
if(o >=1){
printf("%d", (int) n % 8);
}
}
}
void ConvertToHexa( long double n)
{
int i=0;
if(n == 0){
printf("0");
}
else{
if ( n / 16 != 0) {
ConvertToHexa( n / 16);
}
if( h==0){
if( ((int) n%16) != 0){
++i;
}
}
h = h+i;
if(h >=1){
if( (int)n%16 >= 10 ){
switch ( (int) n % 16 )
{
case 10 :
printf ("A");
break;
case 11 :
printf ("B");
break;
case 12 :
printf ("C");
break;
case 13 :
printf ("D");
break;
case 14 :
printf ("E");
break;
case 15 :
printf ("F");
break;
}
}
else{
printf("%d", (int) n % 16);
}
}
}
}