Author Topic: Turbo C - Decimal to Hexadecimal conversion  (Read 2775 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
Turbo C - Decimal to Hexadecimal conversion
« on: December 29, 2011, 12:21:01 pm »
Here is the turbo c program to convert a number from decimal to hexadecimal.


Code:
//Source Code Listing


#include <stdio.h>

void ConvertDecimal2Hexadecimal(int dec, char *buffer)
{
   int hex = 0;
   int i = 0, len = 0;
   char tempArray[128];
   if(dec <= 0)
   {
      buffer[0] = '0';
      buffer[1] = '\0';
      return;
   }
   while(dec > 0)
   {
      hex = dec % 16;
      dec = dec / 16;
      if(hex >= 10)
         tempArray[len++] = hex - 10 + 'A';
      else
         tempArray[len++] = hex + '0';
   }
   
   // do the string reverse
   for(i = len - 1; i >= 0; i--)
      buffer[len - i - 1] = tempArray[i];
   buffer[len] = '\0';
}


int main()
{
   char buf[128];
   int n = 0;
   printf("Program for decimal to Hexadecimal conversion\n");
   printf("Enter a number: ");
   scanf("%d", &n);
   ConvertDecimal2Hexadecimal(n, buf);
   printf("%d = 0x%s\n", n, buf);
   return 0;
}

/****

sample output: 

Program for decimal to Hexadecimal conversion
Enter a number: 1000
1000 = 0x3E8
Press any key to continue . . .

****/



 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1