View Single Post
  #3   Spotlight this post!  
Unread 05-03-2007, 14:59
dcbrown dcbrown is offline
Registered User
AKA: Bud
no team
Team Role: Mentor
 
Join Date: Jan 2005
Rookie Year: 2005
Location: Hollis,NH
Posts: 236
dcbrown has much to be proud ofdcbrown has much to be proud ofdcbrown has much to be proud ofdcbrown has much to be proud ofdcbrown has much to be proud ofdcbrown has much to be proud ofdcbrown has much to be proud ofdcbrown has much to be proud ofdcbrown has much to be proud ofdcbrown has much to be proud of
Re: Quick & Dirty float to string converter

Fixed a couple bugs.

Test cases run:
1.234567879
1.233999963
1234.000000000
1234567936.000000000
0.123399970
0.001233990
0.000012335
0.156250000
98.765434262
9.876543043
0.987654324


Code:
void printff( long fbinary )
{
char sign;
unsigned char exp;
int bias;
long data;
long left;

    sign = ' ';
    if ((fbinary & 0x80000000) != 0) sign = '-';

    exp = (fbinary & 0x7F800000) >> 23; 

    /* compute whole number */
    bias = (int)exp - (int)127;
    if (bias >= 0)
    {
        if (bias <= 30)
        {
	    data = 0x1;
	    while (bias > 0)
	    {
	        data <<= 1;
	        if ((fbinary & 0x00400000) != 0)
		    data |= 0x1;
	        fbinary <<= 1;
	        --bias;
	    }
            printf( "%c%d.", sign, data );
        }
        else
        {
	    // can't do yet
	    printf( "**.****\n");
	    return;
        }

	/* compute fraction */
        data = 0;
        left = 500000000;
	fbinary &= 0x007FFFFF;
        while (fbinary != 0)
        {
	    if ((fbinary & 0x00400000) != 0)
	        data += left;
	    fbinary <<= 1;
	    fbinary &= 0x007FFFFF;
	    left = left >> 1;
        }
        printf( "%09d\n", data );
    }
    else
    {
        /* Number < 1.0 */
        printf( "%c0.", sign );
	bias = -bias;
	if (bias < 24 )
	{
            data = 0;
            left = 500000000;
	    fbinary &= 0x00FFFFFF;
	    fbinary |= 0x00800000;
	    fbinary >>= (bias-1);
            while (fbinary != 0)
            {
	        if ((fbinary & 0x00800000) != 0)
	            data += left;
	        fbinary <<= 1;
	        fbinary &= 0x00FFFFFF;
		left = left >> 1;
            }
            printf( "%09d\n", data );
	}
	else
	{
	    printf( "%09d\n", 0 );
	}
    }
    return;
}
PS I'm not trying to encourage the use of floating point, but for debugging and in small doses it has its uses.