Thread: Weird thing convert float to binary

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    40

    Weird thing convert float to binary

    Hi,
    Could someone please take a look at this function I don't know why it is not working. The compiler just hangs.

    Code:
    void dectohex (float num);
    int main(int argc, char** argv)
    {
       float num2;
         if (argc >= 2)
           num2 = atof(argv[1]);
        else
           scanf("%2.1f", &num2);
    
    
    dectohex(num2);
    
    }
    
    void dectohex (float num)
    {
       float num1;
       int int_part;
      unsigned int i, pos = sizeof(int)*8 - 1;
      const unsigned int int_msb = 1 << (sizeof(int)*8 - 1);
      int_part = num1;
      num1 -= int_part;
       
    if (int_part < 0) {
        putc('-', stdout);
        int_part = -int_part;
        num1 = -num1;
    }
    
    
    for (i = 0; pos; i ++, pos --) {
         if (int_part & (int_msb >> i))
        break;
    }
    for (; pos; pos --) {
        putc(((int_part & (1 << pos)) >> pos) + '0', stdout);
    			}
    putc((int_part & 1)+ '0', stdout);
    
    if (num1)
      putc('.', stdout);
       while (num1) {
       num *= 2;
       putc(((int) num1 & 1), stdout);
       num1 -= (int) num1;
       }
    }
    Last edited by sara.stanley; 02-13-2006 at 02:33 AM.

  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    If your compiler hangs when trying to compile a program, I suggest you start using a new compiler.

    It compiles fine for me except #include <stdio.h> needs to be added.

    There are also a few wrong things, such as %2.1f not making sense for a format specifier in your scanf.

    Also, you can indent code how you like, but when you post code expecting people to look at it, I would suggest you indent it in a reasonable manner.

  3. #3
    Registered User
    Join Date
    Feb 2006
    Posts
    40
    I am using Cygwin. Are you getting the correct output.thanks for the suggestion I indented the code.

  4. #4
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Quote Originally Posted by sara.stanley
    Are you getting the correct output.
    Nope.

  5. #5
    Registered User
    Join Date
    Feb 2006
    Posts
    40
    do you know what the problem is.

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    1. Enable all the warnings, eg.
    Code:
    $ gcc bar.c
    $ gcc -W -Wall -ansi -pedantic -O2 bar.c
    bar.c: In function `main':
    bar.c:9: warning: implicit declaration of function `atof'
    bar.c:11: warning: unknown conversion type character `.' in format
    bar.c:11: warning: too many arguments for format
    bar.c: In function `dectohex':
    bar.c:17: warning: 'num1' might be used uninitialized in this function
    bar.c: In function `main':
    bar.c:13: warning: control reaches end of non-void function
    2. Lack of indentation, and omitting braces where you think they are optional (when in fact they are not) will kill you every time.
    Code:
    #include <stdio.h>
    
    void dectohex(float num);
    
    int main(int argc, char **argv)
    {
        float num2;
        if (argc >= 2)
            num2 = atof(argv[1]);
        else
            scanf("%2.1f", &num2);
        dectohex(num2);
    }
    
    void dectohex(float num)
    {
        float num1;
        int int_part;
        unsigned int i, pos = sizeof(int) * 8 - 1;
        const unsigned int int_msb = 1 << (sizeof(int) * 8 - 1);
        int_part = num1;
        num1 -= int_part;
    
        if (int_part < 0) {
            putc('-', stdout);
            int_part = -int_part;
            num1 = -num1;
        }
    
    
        for (i = 0; pos; i++, pos--) {
            if (int_part & (int_msb >> i))
                break;
        }
    
        for (; pos; pos--) {
            putc(((int_part & (1 << pos)) >> pos) + '0', stdout);
        }
        putc((int_part & 1) + '0', stdout);
    
        if (num1)
            putc('.', stdout);
    
        while (num1) {
            num *= 2;
            putc(((int) num1 & 1), stdout);
            num1 -= (int) num1;
        }
    }
    Can you now spot the infinite loop?

  7. #7
    Registered User
    Join Date
    Feb 2006
    Posts
    40
    thanks, the programs ends but I still don't get the correct result.

  8. #8
    Registered User
    Join Date
    Dec 2005
    Location
    Australia - Melbourne
    Posts
    63
    just compare my code with yours to see what you've done wrong.

    i like how you intend to find the binary code after the decimal.

    i suggest you put comments in your program. since there wasn't any i relied of the names (int_part was particularly helpful), i had to guess what num1 was, lucky i guessed right.

    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    void dectohex (float num);
    
    int main(int argc, char* argv) { // yours was int main(int argc, char** argv) {
        float num2;
        if (argc >= 2) num2 = atof(argv[1]);
        else scanf("%f", &num2); /* you had else scanf("%2.1f", &num2); the number 
                                between the % and f must be an integer and suggests 
                                maximum number of digits + '.' to be read */
        
        dectohex(num2);
        
        system("PAUSE");
        return 0;
    }
    
    void dectohex (float num)
    {
        float num1;
        int int_part;
        unsigned int i, pos = sizeof(int)*8 - 1;
        const unsigned int int_msb = 1 << (sizeof(int)*8 - 1);
        
        /* you had int_part = num1; num1 -= int_part; 
        which you can't do because you haven't declared a value for num1 */
        int_part = (int)num;
        num1 = num;
        num1 -= int_part;
       
        if (int_part < 0) {
            putc('-', stdout);
            int_part = -int_part;
            num1 = -num1;
        }
    
        // finds first set bit in int_part
        for (i = 0; pos; i ++, pos --) if (int_part & (int_msb >> i)) break;
        
        // display binary code for int_part
        for (; pos; pos --) putc(((int_part & (1 << pos)) >> pos) + '0', stdout);
        putc((int_part & 1)+ '0', stdout);
       
        // displays decimal point
        if (num1) putc('.', stdout);
        
        /* displays binary code after decimal place,
           might want to put a restriction on this because of float's 
           precision which will lead to incorrect binary code
           or change to a double. maybe even an infinite loop*/
        while (num1) {
            num1 *= 2;                              // you had num *= 2;
            putc(((int)num1 & 1)+'0', stdout);      // you forgot + '0'
            num1 -= (int)num1;
        }
    }
    Last edited by peterchen; 02-13-2006 at 05:34 AM. Reason: better and more comments

  9. #9
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    When you convert the program to a seperate function you wouldn't need to declare any float for the new function as the float value is being declared as a formal parameter so the num1 is unnecessary.

    [edit] Here's some explanation of the variables meaning and some comments in the code.
    num = The number.
    int_part = The integer part of num
    i = Index, used for incrementation of loops
    pos = The current bit position when processing the integer part
    int_msb = Most Significant Bit for the integer type, i.e the highest bit will be set to 1 and the rest 0 so when int is 32-bit it will look like 10000000 00000000 00000000 00000000

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void dectobin (float num);
    
    int main (int argc, char** argv)
    {
    	float num;
    
    	if (argc >= 2)
    		num = atof(argv[1]);
    	else
    		scanf("%f", &num);	
    	dectobin(num);
    
    	return 0;
    }
    
    void dectobin (float num)
    {
    	               int int_part;
    	      unsigned int i, pos = sizeof(int)*8 - 1;
    	const unsigned int int_msb = 1 << (sizeof(int)*8 - 1);
    
    	/* Splits the number into an integer part and decimal part, this is
    	 * done because we need to know where to put the '.'
    	 */
    	int_part = num;
    	num -= int_part;
    
    	//If the number is negative, change it to positive and write '-' character.
    	if (int_part < 0) {
    		putc('-', stdout);
    		int_part = -int_part;
    		num = -num;
    	}
    
    	/* Find out where to start, i.e. where the first '1' bit is
    	 * Otherwise we'd probably get a long zerofill.
    	 */
    	for (i = 0; pos; i++, pos--) {
    		if (int_part & (int_msb >> i))
    			break;
    	}
    
    	//Traverses the integer part and writes it's binary.
    	for (; pos; pos--) {
    		putc(((int_part & (1 << pos)) >> pos) + '0', stdout);
    	}
    
    	/* pos needs to be 0 for the least significant bit, but that ends the loop.
    	 * Also, this will ensure a 0 in front of a possible '.' so that 
    	 * 0.625 becomes "0.101" and not ".101"
    	 */
    	putc((int_part & 1) + '0', stdout);
    
    	//Don't make me explain this.
    	if (num)
    		putc('.', stdout);
    
    	//Finally prints out the decimal part.
    	while (num) {
    		num *= 2;
    		putc(((int) num & 1) + '0', stdout);
    		num -= (int) num;
    	}
    }
    Last edited by OnionKnight; 02-13-2006 at 09:12 AM.

  10. #10
    Registered User
    Join Date
    Feb 2006
    Posts
    40
    Thanks a lot for all your help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 03-26-2007, 05:48 PM
  2. Convert 10.2 to binary
    By sara.stanley in forum C Programming
    Replies: 20
    Last Post: 02-08-2006, 09:22 AM
  3. Backdooring Instantaneous Radius of Curvature & Functions
    By just2peachy in forum C++ Programming
    Replies: 8
    Last Post: 10-06-2004, 12:25 PM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM