To solve this problem we need to know the steps to convert a decimal number to binary / Octal / Hexadecimal number.
As you all know that conversion from binary to any base follows a single rule. And the rule is:
" To convert a decimal to N_base_number_system we need to divide the decimal by N till we reach to ZERO. In this process we need to store all the reminders and print them in a reversed way "
Take the decimal number from the user
make 3 function for binary, octal, Hexadecimal
For each function we will need a string to store the reminders and print them reversely
In case of hexadecimal we will need to use conditions to get A,B,C,D,E,F
We will convert integer to character using s[n++]=(char)(a%8+(int)'0') this technique.
#include<stdio.h>
void binary(int a){
int n=0;
char s[10000];
while(a>0){
s[n++]=(char)(a%2+(int)'0');
a=a/2;
}
printf("Binary >> ");
for(n=n-1;n>=0;n--){
printf("%c",s[n]);
}
printf("\n");
}
void octal(int a){
int n=0;
char s[10000];
while(a>0){
s[n++]=(char)(a%8+(int)'0');
a=a/8;
}
printf("Octal >> ");
for(n=n-1;n>=0;n--){
printf("%c",s[n]);
}
printf("\n");
}
void hexa(int a){
int n=0,k;
char s[10000];
while(a>0){
k=a%16;
if(k<10) s[n++]=(char)(k+(int)'0');
else if(k==10) s[n++]='A';
else if(k==11) s[n++]='B';
else if(k==12) s[n++]='C';
else if(k==13) s[n++]='D';
else if(k==14) s[n++]='E';
else if(k==15) s[n++]='F';
a=a/16;
}
printf("Hexadecimal >> ");
for(n=n-1;n>=0;n--){
printf("%c",s[n]);
}
printf("\n");
}
int main()
{
int a,choice;
printf("Enter the decimal number :: ");
scanf("%d",&a);
binary(a);
octal(a);
hexa(a);
return 0;
}
Enter the decimal number :: 2345
Binary >> 100100101001
Octal >> 4451
Hexadecimal >> 929