qc.hlp (Table of Contents; Topic list)
MSB.C
                                             Up Contents Index Back
────────────────────────────────────────────────────────────────────────────
 
/* MSB.C illustrates conversion between IEEE floating-point format
 * and MS Binary format. Functions illustrated include:
 *      fieeetomsbin    fmsbintoieee    dieeetomsbin    dmsbintoieee
 *
 * Only fieeetomsbin is specifically used, but the others work the same.
 */
 
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char *binstr32( unsigned long num, char *buffer );  /* Prototype */
 
void main()
{
    union
    {
        float f;            /* As float */
        unsigned long ul;   /* As unsigned long (for binary conversion) */
    } msbin, ieee;
    char tmpmsbin[33], tmpieee[33];
 
    /* Convert an IEEE number to MS binary and show the result in binary. */
    ieee.f = 4.352;
    if( fieeetomsbin( &ieee.f, &msbin.f ) )
    {
        printf( "Can't convert\n" );
        exit( 1 );
    }
 
    /* Convert to binary string. */
    binstr32( msbin.ul, tmpmsbin );
    binstr32( ieee.ul, tmpieee );
    printf( "%f in MS Binary format:\t%32s\n", ieee.f, tmpmsbin );
    printf( "%f in IEEE format:\t%32s\n", ieee.f, tmpieee );
    exit( 0 );
}
 
/* Converts unsigned long to string of 32 binary characters. */
char *binstr32( unsigned long num, char *buffer )
{
    char tmp[33];
    unsigned long len;
 
    memset( buffer, '0', 32 );
    len = strlen( ultoa( num, tmp, 2 ) );
    strcpy( buffer + 32 - len, tmp );
    return buffer;
}