home *** CD-ROM | disk | FTP | other *** search
/ kermit.columbia.edu / kermit.columbia.edu.tar / kermit.columbia.edu / utils / unhex.c < prev    next >
C/C++ Source or Header  |  1999-04-14  |  2KB  |  55 lines

  1. /*  UNHEX.C - Program to translate a hex file from standard input
  2.  *  into an 8-bit binary file on standard output.
  3.  *  Usage: unhex < foo.hex > foo.exe
  4.  *  Christine M. Gianone, CUCCA, October 1986.
  5.  *  Modified Aug 89 to work right with Microsoft C on the PC.
  6.  */
  7.  
  8. #include <stdio.h>            /* Include this for EOF symbol */
  9. #ifdef MSDOS
  10. #include <fcntl.h>            /* For MS-DOS setmode() symbol */
  11. #endif
  12.  
  13. unsigned char a, b;            /* High and low hex nibbles */
  14. unsigned int c;                /* Character to translate them into */
  15. unsigned char decode();            /* Function to decode them  */
  16.  
  17. /* Main program reads each hex digit pair and outputs the 8-bit byte. */
  18.  
  19. main() {
  20. #ifdef MSDOS
  21.     setmode(fileno(stdout),O_BINARY); /* To avoid DOS text-mode conversions */
  22. #endif
  23.     while ((c = getchar()) != EOF) {    /* Read first hex digit */
  24.     a = c;                /* Convert to character */
  25.         if (a == '\n') {        /* Ignore line terminators */
  26.             continue;
  27.     }
  28.     if (a == '\r') {
  29.         fprintf(stderr,"Illegal Carriage Return\n");
  30.         exit(1);
  31.     }
  32.     if ((c = getchar()) == EOF) {    /* Read second hex digit */
  33.         fprintf(stderr,"File ends prematurely\n");
  34.         exit(1);
  35.     }
  36.     b = c;                /* Convert to character */
  37.     putchar( ((decode(a) * 16) & 0xF0) + (decode(b) & 0xF) );
  38.     }
  39.     exit(0);                /* Done */
  40. }
  41.  
  42. unsigned char
  43. decode(x) char x; {              /* Function to decode a hex character */
  44.     if (x >= '0' && x <= '9')         /* 0-9 is offset by hex 30 */
  45.       return (x - 0x30);
  46.     else if (x >= 'A' && x <= 'F')    /* A-F offset by hex 37 */
  47.       return(x - 0x37);
  48.     else if (x >= 'a' && x <= 'f')    /* a-f offset by hex 37 */
  49.       return(x - 0x57);
  50.     else {                            /* Otherwise, an illegal hex digit */
  51.         fprintf(stderr,"\nInput is not in legal hex format\n");
  52.         exit(1);
  53.     }
  54. }
  55.