home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-385-Vol-1of3.iso / s / snip1292.zip / TP6TOD.C < prev    next >
C/C++ Source or Header  |  1991-12-23  |  2KB  |  75 lines

  1. /*
  2. ** Convert Turbo Pascal 6-byte reals to C double format
  3. ** Written by Thad Smith III, Boulder, CO.  12/91
  4. ** Tested on TC 2.01, BC++ 2.0/3.0, QC 2.50, Power C 2.0.1, ZTC 3.0
  5. ** Contributed to the Public Domain.
  6. */
  7.  
  8. #include <math.h>
  9. #include <string.h>
  10. #ifdef TEST
  11.  #include <stdio.h>
  12. #endif
  13.  
  14. /*
  15. ** Specify packed structures.
  16. ** Note: This may not work on some compilers.
  17. */
  18.  
  19. #if __TURBOC__ > 0x0201
  20.  #pragma option -a-
  21. #elif defined __ZTC__
  22.  #pragma ZTC align 1
  23. #else   /* MSC, WATCOM */
  24.  #pragma pack(1)
  25. #endif
  26.  
  27. double tp6_to_double(const unsigned char *tp6)
  28. {
  29.       struct {
  30.             unsigned char be  ;     /* biased exponent           */
  31.             unsigned int  v1  ;     /* lower 16 bits of mantissa */
  32.             unsigned int  v2  ;     /* next  16 bits of mantissa */
  33.             unsigned int  v3:7;     /* upper  7 bits of mantissa */
  34.             unsigned int  s :1;     /* sign bit                  */
  35.       } real;
  36.  
  37.       memcpy (&real, tp6, 6);
  38.       if (real.be == 0)
  39.             return 0.0;
  40.       return (((((128 +real.v3) * 65536.0) + real.v2) * 65536.0 + real.v1) *
  41.             ldexp ((real.s? -1.0: 1.0), real.be - (129+39)));
  42. }
  43.  
  44. #ifdef TEST
  45.  
  46. /*
  47. ** This test program reads 6-byte values, one per line, in
  48. ** 12-digit hexadecimal format from stdin, converts to a double,
  49. ** then prints it.
  50. */
  51.  
  52. void main(void)
  53. {
  54.       unsigned char c[6];
  55.       int buf[6];
  56.       int i, n;
  57.  
  58.       for (;;)
  59.       {
  60.             n = scanf (" %2x%2x%2x%2x%2x%2x", &buf[0], &buf[1], &buf[2],
  61.                                               &buf[3], &buf[4], &buf[5]);
  62.             if (n <= 0)
  63.                   break;
  64.             for (i=0; i < 6; i++)
  65.             {
  66.                   c [i] = buf[i];
  67.                   printf ("%2.2x", buf[i]);
  68.             }
  69.             printf (" =  %lg\n", tp6_to_double (c));
  70.       }
  71.       return 0;
  72. }
  73.  
  74. #endif
  75.