Write a C program to convert the given decimal number to binary, Octal and Hexadecimal

Convert Decimal to Binary:
int main()
{
    long int decimalNumber,remainder,quotient;
    int binaryNumber[100],i=1,j;
    printf("Enter any decimal number: ");
    scanf("%ld",&decimalNumber);
    quotient = decimalNumber;
    while(quotient!=0){
         binaryNumber[i++]= quotient % 2;
         quotient = quotient / 2;
    }
    printf("Equivalent binary value of decimal number %d: ",decimalNumber);
    for(j = i -1 ;j> 0;j--)
         printf("%d",binaryNumber[j]);

    return 0;
}
output:
Enter any decimal number: 50
Equivalent binary value of decimal number 50: 110010
Convert Decimal to Octal:
int main(){
  long int decimalNumber,remainder,quotient;
  int octalNumber[100],i=1,j;

  printf("Enter any decimal number: ");
  scanf("%ld",&decimalNumber);

  quotient = decimalNumber;
  while(quotient!=0){
      octalNumber[i++]= quotient % 8;
      quotient = quotient / 8;
  }
  printf("Equivalent octal value of decimal number %d: ",decimalNumber);
  for(j = i -1 ;j> 0;j--)
      printf("%d",octalNumber[j]);
  return 0;
}
Output:
Enter any decimal number: 50
Equivalent octal value of decimal number 50: 62

2. Easy way to convert decimal number to octal number in c
#include
int main(){
  long int decimalNumber;
  printf("Enter any decimal number : ");
  scanf("%d",&decimalNumber);
  printf("Equivalent octal number is: %o",decimalNumber);
  return 0;
}
output:
Enter any decimal number: 25
Equivalent octal number is: 31
Convert Decimal to Hexadecimal:
int main(){
    long int decimalNumber,remainder,quotient;
    int i=1,j,temp;
    char hexadecimalNumber[100];

    printf("Enter any decimal number: ");
    scanf("%ld",&decimalNumber);

    quotient = decimalNumber;

    while(quotient!=0){
         temp = quotient % 16;

      //To convert integer into character
      if( temp < 10)
           temp =temp + 48;
      else
         temp = temp + 55;

      hexadecimalNumber[i++]= temp;
      quotient = quotient / 16;
  }

    printf("Equivalent hexadecimal value of decimal number %d: ",decimalNumber);
    for(j = i -1 ;j> 0;j--)
      printf("%c",hexadecimalNumber[j]);

    return 0;
}

Output:

Enter any decimal number: 45
Equivalent hexadecimal value of decimal number 45: 2D

2. Easy way to convert decimal number to hexadecimal number:

#include
int main(){

  long int decimalNumber;

  printf("Enter any decimal number: ");
  scanf("%d",&decimalNumber);

  printf("Equivalent hexadecimal number is: %X",decimalNumber);

  return 0;
}

Output:
Enter any decimal number: 45
Equivalent hexadecimal number is: 2D

1 comment: