home *** CD-ROM | disk | FTP | other *** search
/ Piper's Pit BBS/FTP: ibm 0000 - 0009 / ibm0000-0009 / ibm0003.tar / ibm0003 / LCNOW2.ZIP / EXAMPLES / HEXDEMO.C < prev    next >
Encoding:
C/C++ Source or Header  |  1988-06-25  |  867 b   |  50 lines

  1. /*
  2.  * H E X D E M O
  3.  *
  4.  * Demonstrate the conversion of decimal numbers to
  5.  * hexadecimal presentation.
  6.  */
  7.  
  8. char DecToHex(int);
  9.  
  10. int
  11. main(void)
  12. {
  13.     int number;
  14.  
  15.     /*
  16.      * Prompt the user for a number and read it.  Then
  17.      * convert the number to hex and print it.
  18.      */
  19.     printf("Enter a decimal number (0 to 15): ");
  20.     scanf("%d", &number);
  21.     printf("%d -> %c hex\n", number, DecToHex(number));
  22.  
  23.     return (0);
  24. }
  25.  
  26.  
  27. /*
  28.  * DecToHex()
  29.  *
  30.  * Convert a number from decimal to hexadecimal.
  31.  */
  32.  
  33. char
  34. DecToHex(int digit)
  35. {
  36.     char hexchar;
  37.     static char hextab[] = {
  38.         '0', '1', '2', '3', '4', '5', '6', '7',
  39.         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  40.     };
  41.  
  42.     /*
  43.      * Guarantee that the digit is in range (modulo 16) and
  44.      * look up the equivalent hex digit in the conversion table.
  45.      */
  46.     hexchar = hextab[digit % 16];
  47.  
  48.     return (hexchar);
  49. }
  50.