Thread: Create a string in binary from a decimal number

  1. #1
    Registered User
    Join Date
    Jul 2021
    Posts
    20

    Create a string in binary from a decimal number

    Hi.

    My first post here.

    I am attempting to take a decimal number (0-255) and convert it to a binary string.

    Something that looks like 0b01010101 for example.

    Code:
    //CONVERT DECIMAL TO BINARY FUNCTION
    void tobinary(char str[11], int num)
    {
        int i;
        bool bin;
        
        str[0] = '0';
        str[1] = 'b';
        
        for (i=2; i<10; i++)
        {
            bin = (num & 0x80);
            if (bin = 1)
            {
                str[i] = '1';
            }
            else 
            {
                str[i] = '0'; 
            }
            num <<= 1;   
        }
        str[i++] = '\0';
    }
    This is what i have written, but the string just comes out as 0b11111111, no matter what number i give it.

    Not sure what i have done wrong. Is there anything obvious here to the more experienced eye?

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,608
    Do you know the difference between assignment "=" and comparison "=="?

    By the way your compiler should be able to help you solve this issue, insure your compiler is set up to generate warnings and never ignore those warnings.

    From my compiler: "main.c|31|warning: suggest parentheses around assignment used as truth value [-Wparentheses]|"

  3. #3
    Registered User
    Join Date
    Sep 2020
    Posts
    80
    if(bin = 1)
    The equal operator is ==, not =.

  4. #4
    Registered User
    Join Date
    Feb 2019
    Posts
    876
    Another thing: All numeric representations in a computer are binary. When you do
    Code:
    int x = 10;
    This "decimal" 10 is encoded in binary and put in memory (or register) as a binary value. So, you can isolate the bits "directly" (avoiding divisions):
    Code:
    void int2str( char *s, unsigned char n )
    {
      int i = 0;
    
      while ( i < 8 )
      {
        *s++ = '0' + ( ( n & 0x80 ) != 0 );
        n <<= 1;
        i++;
      }
    }

  5. #5
    Registered User
    Join Date
    Jul 2021
    Posts
    20
    Thanks guys.
    I have been coding for about 3 days!!

    I didnt see the = and == differences when looking for similar examples of what i was attempting to do.

    The == has fixed the function tho and it does as i expect it to now.

  6. #6
    Registered User
    Join Date
    Jul 2021
    Posts
    20
    Quote Originally Posted by flp1969 View Post
    Another thing: All numeric representations in a computer are binary. When you do
    Code:
    int x = 10;
    This "decimal" 10 is encoded in binary and put in memory (or register) as a binary value. So, you can isolate the bits "directly" (avoiding divisions):
    Code:
    void int2str( char *s, unsigned char n )
    {
      int i = 0;
    
      while ( i < 8 )
      {
        *s++ = '0' + ( ( n & 0x80 ) != 0 );
        n <<= 1;
        i++;
      }
    }
    This looks much more condensed than how i have gone about it.
    Does this method have much benefit in speed? Or is it just less typing?

  7. #7
    Registered User
    Join Date
    Feb 2019
    Posts
    876
    Quote Originally Posted by Kisen View Post
    This looks much more condensed than how i have gone about it.
    Does this method have much benefit in speed? Or is it just less typing?
    In essence it is the same thing. I've only notice that any comparison results in 0 or 1 (not other values)... The if:
    Code:
    bin = n & 0x80;  // isolate bit 7.
    if ( bin == 1)
      s[i] = '1';
    else
      s[i] = '0';
    Can be substituted by a single line:
    Code:
    s[i] = '0' + ( ( n & 0x80 ) != 0 );
    As for the generated code by the compiler, with optimizations turned on, both codes are the same.

    And, since s points to the beggining of the string, I use it...

    BTW: There is an error in my routine. Before returning it should have:
    Code:
      ...
      *s = '\0';  // puts the end of string mark.
    }

  8. #8
    Registered User
    Join Date
    Apr 2019
    Posts
    100
    Quote Originally Posted by jimblumberg View Post
    Do you know the difference between assignment "=" and comparison "=="?

    By the way your compiler should be able to help you solve this issue, insure your compiler is set up to generate warnings and never ignore those warnings.

    From my compiler: "main.c|31|warning: suggest parentheses around assignment used as truth value [-Wparentheses]|"
    are setting warning level high=warnings is reported as errors something to recommend when newbie or when nasty hard to find bugs like "=" when it should be "==" ?
    single step thru debugger is one way to find bugs ala all kind of typos that dont generate errors but bugs that make code run not as intended
    but automatic compiler checking thru lots of lines of code is better and faster
    you tell me you can C,why dont you C your own bugs?

  9. #9
    Registered User
    Join Date
    Jul 2021
    Posts
    1
    what kind of c extensions do you use for gcc compiler? My compiler only quits with error message, unknown type bool instead of _Bool and so on.
    Maybe compiler extension option will solve this error?

  10. #10
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    836
    Quote Originally Posted by Yamyam View Post
    what kind of c extensions do you use for gcc compiler? My compiler only quits with error message, unknown type bool instead of _Bool and so on.
    Maybe compiler extension option will solve this error?
    If your compiler is using C Standard C99 or later, the you could add:
    Code:
    #include <stdbool.h>
    which would allow the use of "bool" in your code, and provide the two values allowed in a bool variable, "true" and "false".

  11. #11
    Registered User
    Join Date
    May 2010
    Posts
    4,608
    are setting warning level high=warnings is reported as errors something to recommend when newbie or when nasty hard to find bugs like "=" when it should be "==" ?
    IMO, using high warning levels is something to recommend on most occasions.

    By the way I don't find the '=' versus "==" to be a hard to find bug, however setting your compiler to generate a message for this problem really makes it a trivial issue.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. binary number to decimal
    By Amos Bordowitz in forum C Programming
    Replies: 2
    Last Post: 03-30-2014, 02:27 PM
  2. Convert a binary number into a decimal number
    By HTHVampire in forum C++ Programming
    Replies: 7
    Last Post: 07-06-2013, 09:53 AM
  3. Convert 8-digit Binary Number to decimal number
    By yongsheng94 in forum C++ Programming
    Replies: 2
    Last Post: 07-06-2013, 09:47 AM
  4. Typing decimal number and cover it binary number!
    By Kazumi in forum C Programming
    Replies: 32
    Last Post: 04-16-2011, 07:21 PM
  5. Binary Number to Decimal
    By theCanuck in forum C++ Programming
    Replies: 12
    Last Post: 02-09-2011, 11:25 PM

Tags for this Thread