Convert Integer to Binary

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Firecore
    New Member
    • Jul 2007
    • 114

    Convert Integer to Binary

    Is it possible in C?

    Is there a certain formula?
  • archonmagnus
    New Member
    • Jun 2007
    • 113

    #2
    Sure. The general idea works by using remainders. For example, suppose the input value is 9.

    9 / 2^4 = 0 remainder 9
    9 / 2^3 = 1 remainder 1
    1 / 2^2 = 0 remainder 1
    1 / 2^1 = 0 remainder 1
    1 / 2^0 = 1 remainder 0

    [the general equation is (remainder / 2^i)]

    So the returned output would be: "01001" -- which is equivalent to 9

    The most straight-forward way (but not most efficient) to do this in code (for 0 <= input < 256) is:
    [code=c]
    scanf("%d", input);

    for (i = 7; i >= 0; i--)
    {
    output[7 - i] = input / pow(2.0, i);
    input %= (int)pow(2.0, i);
    }

    for (i = 0; i < 8; i++)
    printf("%d", output[i]);
    [/code]
    (Disclaimer: I haven't tested this, but the general idea is the same.)

    Comment

    • iWillLiveforever
      New Member
      • Feb 2007
      • 136

      #3
      It is always possible to convert in any language you just have to do the math.

      I’m guessing the integer is in base 10

      So say you have the number 23 that you want to convert into binary

      23-(2^4)=7
      1

      7-(2^3) =put in a zero
      0

      7-(2^2) =3
      1

      3-(2^1)=1
      1

      1-(2^0)=0
      1

      so 23 base 10 = 10111 binary

      And can someone check my work to make sure its correct.

      Comment

      • linkid
        New Member
        • Jul 2007
        • 1

        #4
        Why do i set y=pow(x,1/3), the result always be "1.000000"?

        For example

        y=pow(8,1/3) ---> y=1.000000

        Comment

        • emaghero
          New Member
          • Oct 2006
          • 85

          #5
          Originally posted by linkid
          Why do i set y=pow(x,1/3), the result always be "1.000000"?

          For example

          y=pow(8,1/3) ---> y=1.000000
          In C/ C++ the pow function takes two arguments. The first argument is of type float or double or int. The second argument must be of type int.

          When you are trying to calculate 8^{1/3} using pow(8,1/3), the second argument is cast into int and as such is rounded to zero, so what you are actually calculating is 8^{0}, which will return 1.

          To calculate numbers to non-integer powers you are better off using a Newton Method approach. If you read up on Newton's Method you will find the answer.

          Also you shouldn't cross-post, hijack another post. It's rude and against the posting guidelines.

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            Originally posted by Firecore
            Is it possible in C?

            Is there a certain formula?
            Use the modulus operator.

            Take 23 as an example. The binary is 10111.

            Do this:

            (23/16) % 2 23/16 which is 1 % 2 which is 1
            (23/8 ) % 2 23/8 which is 2 % 2 which is 0
            (23/4 ) % 2 23/4 which is 5 % 2 which is 1
            (23/2 ) % 2 23/2 which is 11 % 2 which is 1
            (23/1 ) % 2 23/1 which is 23% 2 which is 1

            You can see the bits and I am sure you can write a loop to vary what you divide into 23 by dividing the divisor by 2 on each cycle of the loop.

            Comment

            • Firecore
              New Member
              • Jul 2007
              • 114

              #7
              I see.
              Thank you very much all of you.

              Comment

              • ravenspoint
                New Member
                • Jul 2007
                • 111

                #8
                All very clever. However, it seems to me everyone is thinking in base 10 and forgetting that the computer thinks in base 2. So why not just extract the bits directly, and save on all those divisions?
                Code:
                	int test = 23;
                	char bin[10];
                	char *p = &bin[8];
                	bin[9] = '\0';
                	int mask = 1;
                	while( mask != 512 ) {
                		if(  mask & test )
                			*p-- = '1';
                		else
                			*p-- = '0';
                		mask <<= 1;
                	}
                	printf("%d -> %s\n",test,bin);

                Comment

                • ilikepython
                  Recognized Expert Contributor
                  • Feb 2007
                  • 844

                  #9
                  Originally posted by ravenspoint
                  All very clever. However, it seems to me everyone is thinking in base 10 and forgetting that the computer thinks in base 2. So why not just extract the bits directly, and save on all those divisions?
                  Code:
                  	int test = 23;
                  	char bin[10];
                  	char *p = &bin[8];
                  	bin[9] = '\0';
                  	int mask = 1;
                  	while( mask != 512 ) {
                  		if(  mask & test )
                  			*p-- = '1';
                  		else
                  			*p-- = '0';
                  		mask <<= 1;
                  	}
                  	printf("%d -> %s\n",test,bin);
                  That's pretty good, never would have thought of it, but I think this is easier:
                  [code=cpp]
                  bitset<8> thirty(30);
                  cout << thirty << endl; // "0001 1110"
                  [/code]

                  Comment

                  • ravenspoint
                    New Member
                    • Jul 2007
                    • 111

                    #10
                    It certainly is easier!

                    I had never come across that class before.

                    I wonder, though, if it is not easier to remember how to use the bitwise operators ( there are only two or three of them ) rather than the names and methods of all these obscure 'standard' classes.

                    Comment

                    • archonmagnus
                      New Member
                      • Jun 2007
                      • 113

                      #11
                      Originally posted by ravenspoint
                      However, it seems to me everyone is thinking in base 10 and forgetting that the computer thinks in base 2. So why not just extract the bits directly, and save on all those divisions? ...
                      Hence my earlier statement, "[B]ut not most efficient".

                      Also, it's been a long time since I used C. The OP's question asked how to do it in C. I've known about bitset in C++, but is it legal in standard C? I would have thought the method ravenspoint showed to be nearly the best you could get in standard C.

                      Comment

                      • ilikepython
                        Recognized Expert Contributor
                        • Feb 2007
                        • 844

                        #12
                        Originally posted by archonmagnus
                        Hence my earlier statement, "[B]ut not most efficient".

                        Also, it's been a long time since I used C. The OP's question asked how to do it in C. I've known about bitset in C++, but is it legal in standard C? I would have thought the method ravenspoint showed to be nearly the best you could get in standard C.
                        Yes, you're right, i didn't pay attention that the OP mentioned C. ravenspoint's method is definately one of the best ways to do it in C. The bitset would be the C++ "way".

                        Comment

                        • ravenspoint
                          New Member
                          • Jul 2007
                          • 111

                          #13
                          OK, if we are going to use my method, let's clean it up a bit and use a more natural left to right scan.
                          [CODE=c]
                          int test = 23; // number to convert
                          char bin[10]; // storage for converted binary coded string
                          char *p = bin; // storage pointer
                          int mask = 256; // start with most significant bit
                          while( mask ) { // until no significance remains
                          if( mask & test ) // is bit set?
                          *p++ = '1'; // yes
                          else
                          *p++ = '0'; // no
                          mask >>= 1; // decrease significance
                          }
                          *p = '\0'; // null terminate string
                          printf("%d -> %s\n",test,bin) ; // ta-da !
                          [/CODE]

                          Comment

                          • Darryl
                            New Member
                            • May 2007
                            • 86

                            #14
                            The problem with ravenspoint is that the number he is converting from is an int but he limits the bitmask to 256, so if someone tried it with a larger integer it would fail.

                            Here is my solution for 32 bit unsigned integers. Technically, though I should use limits.h to find out exactly the number of bits the particular machine/compiler is using to truly make it portable.

                            [CODE=c]int main()
                            {
                            char bits[33]="0000000000000 000000000000000 0000";
                            int index=0;

                            unsigned number = 23;
                            unsigned copy = number;

                            while(copy>0) bits[31-index++]='0'+ (1 & copy), copy>>=1;

                            printf("%d -> %s\n",number , bits);
                            }[/CODE]

                            I had a simpler method but it required bool which is not C.

                            Comment

                            • ravenspoint
                              New Member
                              • Jul 2007
                              • 111

                              #15
                              Originally posted by Darryl
                              The problem with ravenspoint is that the number he is converting from is an int but he limits the bitmask to 256, so if someone tried it with a larger integer it would fail.

                              Here is my solution for 32 bit unsigned integers. Technically, though I should use limits.h to find out exactly the number of bits the particular machine/compiler is using to truly make it portable.

                              [CODE=c]int main()
                              {
                              char bits[33]="0000000000000 000000000000000 0000";
                              int index=0;

                              unsigned number = 23;
                              unsigned copy = number;

                              while(copy>0) bits[31-index++]='0'+ (1 & copy), copy>>=1;

                              printf("%d -> %s\n",number , bits);
                              }[/CODE]
                              Problem in line #9 - the "," should be a ";" I think.

                              It is not good to cram so much code into one line, The compiler can keep it all straight, but it hurts my head to look at it!

                              Comment

                              Working...