Convert 10.2 to binary

This is a discussion on Convert 10.2 to binary within the C Programming forums, part of the General Programming Boards category; Hi, How can I convert 0.00 to a binary number. I know how to convert with just the decimal.But how ...

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

    Convert 10.2 to binary

    Hi,

    How can I convert 0.00 to a binary number. I know how to convert with just the decimal.But how can I convert using a fractional part. I know how to do it on paper but I am having a hard time writing a program for it. Any help is appreciated.

    My program that converts decimal to binary:

    Code:
    #include <stdio.h>
    
    void dec_bin(int number);
    
    int main(void) {
     int input = 0;
    
     printf("Digit (0-255): ");
     scanf("%d", &input);
    
     (input >= 0) && (input < 256) ? dec_bin(input) : exit(1);
    
     return 0;
    }
    
    void dec_bin(int number) {
     int x, y;
     x = y = 0;
    
     for(y = 7; y >= 0; y--) {
      x = number / (1 << y);
      number = number - x * (1 << y);
      printf("%d", x);
     }
    
     printf("\n");
    }

  2. #2
    Registered User
    Join Date
    Feb 2006
    Posts
    40
    Does anyone have any suggestions.

  3. #3
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    you could use a function like this
    Code:
    void float_bin( float f ) {
    	unsigned char * cp = (unsigned char *)&f;
    	int i;
    	for ( i = 0; i < sizeof(f); ++i )
    	   dec_bin((unsigned char )cp[i]);
    }
    It uses your function dec_bin().
    Kurt

  4. #4
    Registered User
    Join Date
    Jan 2006
    Posts
    8
    That's what I was able to get:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    int FractionalBinary(float num ,int DEC, int PREC);
    int main()
    {
        /**************** PUT YOUR NUMBER HERE **************/
        float n = 0.51;
        
        FractionalBinary(n,1000,10);
        system("PAUSE");
    }
    
    
    int FractionalBinary(float num ,int DEC, int PREC)
    {
    /* Calculates binary equivalent of fractional part of a decimal number.
     * NUM is the number to process;
     * DEC is the number of decimal figures to be taken into account
     * PREC is the max number of "1" figures allowed in the binary equivalent:
            the more it's high, the most the result is close to the actually
            received value.
    */
        int loops = 0;
        int pot = 0;
        int add = 0;
        int figures = 0;
        float kkk;
        
        kkk = num;
        printf("Binary equivalent of %f is...\n",num);
        while (loops <= PREC)
            {
            pot = 0;
            num=num*DEC; /* Turn fractional into integer. */
            while ((num<DEC) && (figures<6)) /* FIGURES limite is needed in case of
                                              * "exact" numbers such as 0.5 (1/2),
                                              * 0.25 (1/2^2) and so on. */
            {
                /* Continue multiplying by 2 the NUM nutil it gets greather
                 * than requested PRECision: when it's true, show a "1"; else a "0".
                 * The product  "num * 2^pot" remains costant: it's the number to be
                 * processed.
                 * Example:
                 * 0.237 = 237/1000 = 2*237/1000 *2^-1 (= 474/1000 * 2^-1) = 474*2/1000 * 2^-2 =
                 * (= 948/1000 * 2^-2) = 948*2/1000 * 2^-3 = 1896/1000 * 2^-3
                 * 1896 is greater than 1000: 1896/1000 * 2^-3 equals to 1/1000 * 2^-3 + 896/1000 * 2^-3 :
                 * store the "1" and repeat cycle for remaining 896.
                 * Cycle can go on till infinite if not stopped by PREC!!!
                 */
                pot++;
                figures++;
                num = num * 2;
                printf("0");
            }
            figures++;
            printf("1");
            add = add + (int)pow(2,pot);
            num = num-DEC;
            loops++;
        }
        printf("\n");
        printf("To verify, divide by: %d: you should get APPROXIMATELY %f\n\n",(int)pow(2,figures),kkk);
        return add;
    }

  5. #5
    Registered User
    Join Date
    Feb 2006
    Posts
    40
    thanks to both of you but both of the solutions doesnot work. I tried 0.625 and it gives me these options
    00000000
    00000000
    00100000
    00111111 and none of them are correct.

    this is ZuK function I am talking about.
    Any other ideas.

    I am using it like this:
    Code:
    #include <stdio.h>
    
    void dec_bin(int number);
    void float_bin( float f );
    
    int main(void) {
    float input = 0;
    
    
     scanf("%f", &input);
    (input >= 0) && (input < 256) ? float_bin(input) : exit(1);
    
    
     return 0;
    
    }
    
    void dec_bin(int number) {
     int x, y;
     x = y = 0;
    
     for(y = 7; y >= 0; y--) {
      x = number / (1 << y);
      number = number - x * (1 << y);
      printf("%d", x);
     }
    
     printf("\n");
    }
    
    void float_bin( float f ) {
    	unsigned char * cp = (unsigned char *)&f;
    	int i;
    	for ( i = 0; i < sizeof(f); ++i )
    	   dec_bin((float )cp[i]);
    }

  6. #6
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    the function works for me
    my output for 0.625
    Code:
    00000000
    00000000
    00100000
    00111111
    same value written into a file in a hex-editor
    Code:
    00 00 20 3F
    what are you expecting ?
    BTW there are different implementations of float.
    Kurt

  7. #7
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Location
    Umeň, Sweden
    Posts
    555
    He wanted the value of a float written in binary, not the raw data of a float.
    Expected output of 0.625 should be 0.101

  8. #8
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    sorry I don't see how 0.101 woud be 0.625.
    Kurt

  9. #9
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    Quote Originally Posted by ZuK
    sorry I don't see how 0.101 woud be 0.625.
    Kurt
    .1 binary = .5 decimal
    .001 binary = .125 decimal
    .1 (binary) + .001 (binary) = .5 (decimal) + .125 (decimal)
    .101 (binary) = .625 (decimal)
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  10. #10
    Registered User
    Join Date
    Dec 2005
    Posts
    52
    here's my integer conversion algorithm, from base 10 to any base 2-36. you could modify it to work with floating point nubmers, if you want to. let me know if you make any successful modifications.
    (PS: sorry for total lack of comments)

    source in C:
    Code:
    /*Functions:
    toch - integer to character, E.G 10 becomes A, 15 becomes F....
    toi - reverse of toch. (character to integer)
    leng - my own strlen.  because i felt like it.
    revstr - flips a string.  asdf becomes fdsa.
    itob - integer to base (integer, base)
    btoi - base to integer (integer as string, base converting FROM)
    */
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <math.h>
    
    char toch(int w);
    int leng(char* str);
    void revstr(char* str);
    char* itob(int n, int r);
    int btoi(char* num, int r);
    
    char toch(int w) {
    	if (w > 9) return (w + 55);
    	else return (w + 48);
    }
    
    int toi(char w) {
    	if (w > 64) return (w - 55);
    	else return (w - 48);
    }
    
    int leng(char* str) {
      int x;
      for (x = 0; str[x] != 0; x++) {}
      return x;
    }
    
    void revstr(char* str) {
      char tmp;
      int l = leng(str), l2 = l - 1, ong;
      for (ong = 0; ong < (l / 2); ong++) {
        tmp = str[ong];
        str[ong] = str[l2 - ong];
        str[l2 - ong] = tmp;
      }
    }
    
    char* itob(int n, int r) {
    	char* tmpstr = malloc(sizeof(char) * 1024);
    	int m;
    	for (m = 0; (n % (int)pow(r, m)) != n; m++) {
    		tmpstr[m] = toch((n % (int)pow(r, m + 1)) / (int)pow(r, m));
    		n -= n % (int)pow(r, m + 1);
    	}
    	tmpstr[m+1] = toch((n % (int)pow(r, m+1)) / (int)pow(r, m));
    	revstr(tmpstr);
    	return tmpstr;
    }
    
    int btoi(char* num, int r) {
    	int l = leng(num), ans = 0, ong;
    	for (ong = 1; l - ong >= 0; ong++) {
    		ans += toi(num[l - ong]) * (int)pow(r, ong - 1);
    	}
    	return ans;
    }

    and in C++:

    Code:
    /* there are some unused functions i think.... and they're not perfect.
    the ones that are there - you can figure them out, they're like the ones from the C version*/
    #include <iostream>
    #include <cmath>
    using namespace std;
    
    char toch(int w) {
      if (w > 9) return (w + 55);
      else return (w + 48);
    }
    
    int toi(char w) {
      if (w > 64) return (w - 55);
      else return (w - 48);
    }
    
    string revstr(string str) {
      char tmp;
      int l = str.length(), l2 = l - 1, ong;
      for (ong = 0; ong < (l / 2); ong ++) {
        tmp = str[ong];
        str[ong] = str[l2 - ong];
        str[l2 - ong] = tmp;
      }
      return str;
    }
    
    string tostr(char x) {
      string ans = "" + x;
      return ans;
    }
    
    string itob(int n, int r) {
      string blah;
      int m;
      char tmp;
      int l, l2, ong;
      for (m = 0; (n % (int)pow((float)r, (float)m)) != n; m++) {
        blah += toch((n % (int)pow((float)r, (float)(m + 1))) / (int)pow((float)r, (float)m));
        n -= n % (int)pow((float)r, (float)(m + 1));
      }
      blah += toch((n % (int)pow((float)r, (float)(m + 1))) / (int)pow((float)r, (float)m));
      return revstr(blah);
    }
    
    int btoi(string num, int r) {
      int l = num.length(), ans = 0, ong;
      for (ong = 1; l - ong >= 0; ong++)
        ans += toi(num[l - ong]) * (int)pow((float)r, (float)(ong - 1));
      return ans;
    }

    Please give me credit if you decide to use these..... also, if you manage to get it to work with floating points (i haven't tried yet) post results here!

  11. #11
    Registered User
    Join Date
    Feb 2006
    Posts
    5
    The thing here is to multiply instead of divide like you do it in your program for decimals. What I mean is whith the example of .625

    .625*2=1.250 so if you get 1 as integer, you should write a 1 in your program.
    the next step is
    .250*2=0.5 So there isn't a one like integer you write 0.
    the final step is 0.5 * 2 = 1.0 so you write the one.

    The ouput as seen is 0.101

    Another examply would be .5

    .5 * 2 = 1.0

    So you write 1 after the period. .5 decimal equals 0.1 binary.

    This is how, the algortith isn't difficult to write in your program.

  12. #12
    Registered User
    Join Date
    Dec 2005
    Location
    Australia - Melbourne
    Posts
    63
    go to this site - read the "Conversion to and from other numeral systems" section

    http://en.wikipedia.org/wiki/Binary_numeral_system

  13. #13
    Registered User
    Join Date
    Jan 2006
    Posts
    8
    I spend some hours to correct my algoriothm... then I found how to "compact" it into a single formula:

    B = 2^PREC * N

    !!! That's incredible!!!

    I put both result in this source:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    int FractionalBinary(float num ,int DEC, int PREC);
    int main()
    {
        /**************** PUT YOUR NUMBER HERE **************/
        float n = 0.625;
        int PREC,DEC;
        
        PREC = 10;
        DEC = 1000;
        
        FractionalBinary(n,DEC,PREC);
        printf("%f=%d/%d\n",n,(int)(pow(2,PREC)*n),(int)pow(2,PREC));
        system("PAUSE");
    }
    
    
    int FractionalBinary(float num ,int DEC, int PREC)
    {
    /* Calculates binary equivalent of fractional part of a decimal number.
     * NUM is the number to process;
     * DEC is the number of decimal figures to be taken into account
     * PREC is the max number of "1" figures allowed in the binary equivalent:
            the more it's high, the most the result is close to the actually
            received value.
    */
        int loops = 0;
        int pot = 0;
        int add = 0;
        int figures = 0;
        float kkk;
        
        kkk = num;
        printf("Binary equivalent of %f is...\n",num);
        num=num*DEC; /* Turn fractional into integer. */
        pot = 0;
        while ((loops <= PREC) && (num>0))
            {
            while ((num<DEC) && (figures<6) && (num>0)) /* FIGURES limite is needed in case of
                                              * "exact" numbers such as 0.5 (1/2),
                                              * 0.25 (1/2^2) and so on. */
            {
    //            printf("(%d),   %f   - 0\n",pot,num);
                printf("0",pot,num);
                /* Continue multiplying by 2 the NUM nutil it gets greather
                 * than requested PRECision: when it's true, show a "1"; else a "0".
                 * The product  "num * 2^pot" remains costant: it's the number to be
                 * processed.
                 * Example:
                 * 0.237 = 237/1000 = 2*237/1000 *2^-1 (= 474/1000 * 2^-1) = 474*2/1000 * 2^-2 =
                 * (= 948/1000 * 2^-2) = 948*2/1000 * 2^-3 = 1896/1000 * 2^-3
                 * 1896 is greater than 1000: 1896/1000 * 2^-3 equals to 1/1000 * 2^-3 + 896/1000 * 2^-3 :
                 * store the "1" and repeat cycle for remaining 896.
                 * Cycle can go on till infinite if not stopped by PREC!!!
                 */
                figures++;
                pot++;
                num = num * 2;
            }
    //            printf("  (%d),   %f   - 1\n",pot,num);
                printf("1",pot,num);
                add = add + (int)pow(2,pot);
    //            printf ("   num-DEC=%f-%d = %d\n",num,DEC,(int)num-DEC);
                num = (int)num-DEC;
                num = num * 2;
                pot++;
                loops++;
            }
        printf("\n");
        printf("To verify, divide by: %d: you should get APPROXIMATELY %f\n\n",(int)pow(2,figures+1),kkk);
        printf("%f = %d/%d\n",kkk,(int)add/2,(int)pow(2,figures+1));
        return add/2;
    }

    My formula means that, for example, 0.625 can be represented in this form:
    N = 0.625
    PREC = 10 (number of bits of precision)
    B = 2^PREC * N = 1024*.625 = 640

    and

    N = B/2^PREC

    i.e., 0.625 = 640/1024

    So, you have just to turn 640 into its binary form: 1010000000
    Of course, 640/1024 can be reduced to 5/8... but I don't know the algorithm...
    This would result in:
    B = 2^PREC * N = 2^3 * .625 = 5 = bin 101

  14. #14
    Registered User
    Join Date
    Jan 2006
    Posts
    8
    Well, actually I see my new "fixed" algorithm... now just works ONLY with 0.625!! LOL
    OK, but the formula is correct, just use it!

  15. #15
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Location
    Umeň, Sweden
    Posts
    555
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main (int argc, char** argv)
    {
    	             float num;
    	               int int_part;
    	      unsigned int i, pos = sizeof(int)*8 - 1;
    	const unsigned int int_msb = 1 << (sizeof(int)*8 - 1);
    	//lol pyramid
    
    	if (argc >= 2)
    		num = atof(argv[1]);
    	else
    		scanf("%f", &num);
    	int_part = num;
    	num -= int_part;
    	if (int_part < 0) {
    		putc('-', stdout);
    		int_part = -int_part;
    		num = -num;
    	}
    
    	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 (num)
    		putc('.', stdout);
    
    	while (num) {
    		num *= 2;
    		putc(((int) num & 1) + '0', stdout);
    		num -= (int) num;
    	}
    
    	return 0;
    }

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 06-16-2011, 11:59 AM
  2. 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
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM
  4. convert word to binary
    By Supra in forum C Programming
    Replies: 13
    Last Post: 03-31-2002, 11:39 AM
  5. Convert a text file to a binary file
    By Cyber Kitten in forum C Programming
    Replies: 16
    Last Post: 02-04-2002, 07:53 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21