Convert decimal to binary












4














This program converts a decimal number to a binary number. This is one of my first C programs and I am wondering if I have used the elements of this language properly. Suggestions for improvement are welcome.



#include <stdio.h>
#include <string.h>

void print_out_reversed(char string)
{
int index = strlen(string);

while (string[index] != '')
index--;

for (int i = index; i >= 0; i--)
putchar(string[i]);
putchar('n');
}

void print_decimal_number_binary(int number)
{
if (number == 0)
{
printf("0n");
return;
}

char bits[sizeof(int) * 8 + 1] = {0};
int index = 0;

while (number > 0)
{
if (number % 2 == 0)
{
bits[index] = '0';
}
else
{
bits[index] = '1';
}
number = number / 2;
index++;
}

print_out_reversed(bits);
}

int main()
{
printf("enter number: ");
int number;
scanf("%i", &number);
print_decimal_number_binary(number);
}









share|improve this question









New contributor




Vengeancos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    4














    This program converts a decimal number to a binary number. This is one of my first C programs and I am wondering if I have used the elements of this language properly. Suggestions for improvement are welcome.



    #include <stdio.h>
    #include <string.h>

    void print_out_reversed(char string)
    {
    int index = strlen(string);

    while (string[index] != '')
    index--;

    for (int i = index; i >= 0; i--)
    putchar(string[i]);
    putchar('n');
    }

    void print_decimal_number_binary(int number)
    {
    if (number == 0)
    {
    printf("0n");
    return;
    }

    char bits[sizeof(int) * 8 + 1] = {0};
    int index = 0;

    while (number > 0)
    {
    if (number % 2 == 0)
    {
    bits[index] = '0';
    }
    else
    {
    bits[index] = '1';
    }
    number = number / 2;
    index++;
    }

    print_out_reversed(bits);
    }

    int main()
    {
    printf("enter number: ");
    int number;
    scanf("%i", &number);
    print_decimal_number_binary(number);
    }









    share|improve this question









    New contributor




    Vengeancos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      4












      4








      4







      This program converts a decimal number to a binary number. This is one of my first C programs and I am wondering if I have used the elements of this language properly. Suggestions for improvement are welcome.



      #include <stdio.h>
      #include <string.h>

      void print_out_reversed(char string)
      {
      int index = strlen(string);

      while (string[index] != '')
      index--;

      for (int i = index; i >= 0; i--)
      putchar(string[i]);
      putchar('n');
      }

      void print_decimal_number_binary(int number)
      {
      if (number == 0)
      {
      printf("0n");
      return;
      }

      char bits[sizeof(int) * 8 + 1] = {0};
      int index = 0;

      while (number > 0)
      {
      if (number % 2 == 0)
      {
      bits[index] = '0';
      }
      else
      {
      bits[index] = '1';
      }
      number = number / 2;
      index++;
      }

      print_out_reversed(bits);
      }

      int main()
      {
      printf("enter number: ");
      int number;
      scanf("%i", &number);
      print_decimal_number_binary(number);
      }









      share|improve this question









      New contributor




      Vengeancos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      This program converts a decimal number to a binary number. This is one of my first C programs and I am wondering if I have used the elements of this language properly. Suggestions for improvement are welcome.



      #include <stdio.h>
      #include <string.h>

      void print_out_reversed(char string)
      {
      int index = strlen(string);

      while (string[index] != '')
      index--;

      for (int i = index; i >= 0; i--)
      putchar(string[i]);
      putchar('n');
      }

      void print_decimal_number_binary(int number)
      {
      if (number == 0)
      {
      printf("0n");
      return;
      }

      char bits[sizeof(int) * 8 + 1] = {0};
      int index = 0;

      while (number > 0)
      {
      if (number % 2 == 0)
      {
      bits[index] = '0';
      }
      else
      {
      bits[index] = '1';
      }
      number = number / 2;
      index++;
      }

      print_out_reversed(bits);
      }

      int main()
      {
      printf("enter number: ");
      int number;
      scanf("%i", &number);
      print_decimal_number_binary(number);
      }






      beginner c






      share|improve this question









      New contributor




      Vengeancos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Vengeancos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 5 hours ago





















      New contributor




      Vengeancos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 6 hours ago









      Vengeancos

      614




      614




      New contributor




      Vengeancos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Vengeancos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Vengeancos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          2 Answers
          2






          active

          oldest

          votes


















          4














          Terminology



          It's important to be able to understand (and describe) what's actually going on. Your program




          1. converts from an integer decimal string representation to an integer using scanf. This integer is then represented as a binary number in the processor.

          2. converts from that integer back into a string representation, but rather than it being decimal, it's binary.


          So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".



          Use const



          void print_out_reversed(char string)


          doesn't modify string, so write const char string.



          Simplify your strlen usage



          This:



          int index = strlen(string);

          while (string[index] != '')
          index--;

          for (int i = index; i >= 0; i--)
          putchar(string[i]);


          can be



          for (int i = strlen(string)-1; i >= 0; i--)
          putchar(string[i]);


          It seems that you don't trust what strlen is doing, which is why you have that intermediate while loop. But that loop won't have any effect, because the null terminator will always be where strlen says it is.



          Use math instead of if



          This:



              if (number % 2 == 0)
          {
          bits[index] = '0';
          }
          else
          {
          bits[index] = '1';
          }


          can be



          bits[index] = '0' + (number & 1);


          Use combined operation and assignment



          This:



          number = number / 2;


          should be



          number /= 2;


          or, for speed (which the compiler will do for you anyway)



          number >>= 1;





          share|improve this answer





























            0














            #include stdio.h
            #include string.h

            void get_bits(void * num, char * out, int bytes);

            int main(void)
            {
            int x = 0;

            printf("Enter an integer: ");
            scanf("%i", &x);

            char bits[65] = {0};
            get_bits(&x, bits, 4);

            printf("%d in binary %sn", x, bits);

            return 0;
            }

            //assumes char array of length 1 greater than
            //number of bits

            void get_bits(void * num, char *out, int bytes)
            {
            unsigned long long filter = 0x8000000000000000;
            unsigned long long temp;

            if(bytes <= 0) return;
            if(bytes > 8) bytes = 8;

            filter = filter >> (8*(sizeof(unsigned long long)-bytes));
            memcpy(&temp, num, bytes);
            int bits = 8*bytes;
            for(int i=0;i<bits;i++) {
            if(filter & temp)
            out[i] = '1';
            else
            out[i] = '0';

            temp = temp << 1;
            }
            out[bits] = '';
            }


            EDIT



            Sorry, I just realized what Code Review meant. I figured I was suggesting an improvement, but I see how it did not match the intent here. Maybe this is closer.



            Improvements



            The posted code requires several loops, divisions, and modulus calculations. While it does solve the problem of representing an integer in binary, the utility may be limited by additional clock cycles.



            The code may be optimized and extended to use with other integer representations, including char, short, or long long (or long depending on the size of long).



            One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.



            Alternative Solution



            The function get_bits will accept any integer representation (presumably floating-point numbers as well, though I have not used it for this and not tested it).



            It will "return," really populate, a character array with up to a 64-bit bit representation of the number.



            It does rely on memcpy from string.h.



            Inputs for get_bits



            void *num : a pointer to the memory address of the number to be represented in
            binary



            char *out : the address of a character array to store the bit representation.

            NOTE: This should be of length 1 longer than the number of bits to
            be represented



            int bytes : number of bytes containing the number to represent in binary



            Implementation



            Based on the size of the data type of the number to be represented, a mask is established with the highest bit set. This is the variable, filter, of type unsigned long long contained in 64-bits. Using bit shifting, a time requirement of 1 clock cycle, the filter is shifted to the right to align it with the highest bit of the number.



            Ex. In hexadecimal, a 16-bit filter would be 0x8000, which in binary is 100000000000000.



            The number is copied to a 64-bit block of memory, temp. After using memcpy of the standard c library, only a single for loop is performed to populate the output string. In each iteration of the loop, a bit-wise AND is performed with filter and temp. The result of this expression is either 0 or non-zero. The result is 0 only, when the highest order bit of temp is 0. The position in the output string is set to 1 if non-zero or 0 otherwise.



            At the end of each iteration the temp is shifted by 1 bit to the left.



            Ex. In binary, if temp is 1010, then temp << 1 is 0100. (a suitable filter would be 1000 in binary)






            share|improve this answer










            New contributor




            RJM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.


















            • Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
              – Sᴀᴍ Onᴇᴌᴀ
              3 hours ago











            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });






            Vengeancos is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210909%2fconvert-decimal-to-binary%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            4














            Terminology



            It's important to be able to understand (and describe) what's actually going on. Your program




            1. converts from an integer decimal string representation to an integer using scanf. This integer is then represented as a binary number in the processor.

            2. converts from that integer back into a string representation, but rather than it being decimal, it's binary.


            So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".



            Use const



            void print_out_reversed(char string)


            doesn't modify string, so write const char string.



            Simplify your strlen usage



            This:



            int index = strlen(string);

            while (string[index] != '')
            index--;

            for (int i = index; i >= 0; i--)
            putchar(string[i]);


            can be



            for (int i = strlen(string)-1; i >= 0; i--)
            putchar(string[i]);


            It seems that you don't trust what strlen is doing, which is why you have that intermediate while loop. But that loop won't have any effect, because the null terminator will always be where strlen says it is.



            Use math instead of if



            This:



                if (number % 2 == 0)
            {
            bits[index] = '0';
            }
            else
            {
            bits[index] = '1';
            }


            can be



            bits[index] = '0' + (number & 1);


            Use combined operation and assignment



            This:



            number = number / 2;


            should be



            number /= 2;


            or, for speed (which the compiler will do for you anyway)



            number >>= 1;





            share|improve this answer


























              4














              Terminology



              It's important to be able to understand (and describe) what's actually going on. Your program




              1. converts from an integer decimal string representation to an integer using scanf. This integer is then represented as a binary number in the processor.

              2. converts from that integer back into a string representation, but rather than it being decimal, it's binary.


              So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".



              Use const



              void print_out_reversed(char string)


              doesn't modify string, so write const char string.



              Simplify your strlen usage



              This:



              int index = strlen(string);

              while (string[index] != '')
              index--;

              for (int i = index; i >= 0; i--)
              putchar(string[i]);


              can be



              for (int i = strlen(string)-1; i >= 0; i--)
              putchar(string[i]);


              It seems that you don't trust what strlen is doing, which is why you have that intermediate while loop. But that loop won't have any effect, because the null terminator will always be where strlen says it is.



              Use math instead of if



              This:



                  if (number % 2 == 0)
              {
              bits[index] = '0';
              }
              else
              {
              bits[index] = '1';
              }


              can be



              bits[index] = '0' + (number & 1);


              Use combined operation and assignment



              This:



              number = number / 2;


              should be



              number /= 2;


              or, for speed (which the compiler will do for you anyway)



              number >>= 1;





              share|improve this answer
























                4












                4








                4






                Terminology



                It's important to be able to understand (and describe) what's actually going on. Your program




                1. converts from an integer decimal string representation to an integer using scanf. This integer is then represented as a binary number in the processor.

                2. converts from that integer back into a string representation, but rather than it being decimal, it's binary.


                So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".



                Use const



                void print_out_reversed(char string)


                doesn't modify string, so write const char string.



                Simplify your strlen usage



                This:



                int index = strlen(string);

                while (string[index] != '')
                index--;

                for (int i = index; i >= 0; i--)
                putchar(string[i]);


                can be



                for (int i = strlen(string)-1; i >= 0; i--)
                putchar(string[i]);


                It seems that you don't trust what strlen is doing, which is why you have that intermediate while loop. But that loop won't have any effect, because the null terminator will always be where strlen says it is.



                Use math instead of if



                This:



                    if (number % 2 == 0)
                {
                bits[index] = '0';
                }
                else
                {
                bits[index] = '1';
                }


                can be



                bits[index] = '0' + (number & 1);


                Use combined operation and assignment



                This:



                number = number / 2;


                should be



                number /= 2;


                or, for speed (which the compiler will do for you anyway)



                number >>= 1;





                share|improve this answer












                Terminology



                It's important to be able to understand (and describe) what's actually going on. Your program




                1. converts from an integer decimal string representation to an integer using scanf. This integer is then represented as a binary number in the processor.

                2. converts from that integer back into a string representation, but rather than it being decimal, it's binary.


                So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".



                Use const



                void print_out_reversed(char string)


                doesn't modify string, so write const char string.



                Simplify your strlen usage



                This:



                int index = strlen(string);

                while (string[index] != '')
                index--;

                for (int i = index; i >= 0; i--)
                putchar(string[i]);


                can be



                for (int i = strlen(string)-1; i >= 0; i--)
                putchar(string[i]);


                It seems that you don't trust what strlen is doing, which is why you have that intermediate while loop. But that loop won't have any effect, because the null terminator will always be where strlen says it is.



                Use math instead of if



                This:



                    if (number % 2 == 0)
                {
                bits[index] = '0';
                }
                else
                {
                bits[index] = '1';
                }


                can be



                bits[index] = '0' + (number & 1);


                Use combined operation and assignment



                This:



                number = number / 2;


                should be



                number /= 2;


                or, for speed (which the compiler will do for you anyway)



                number >>= 1;






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 5 hours ago









                Reinderien

                3,743821




                3,743821

























                    0














                    #include stdio.h
                    #include string.h

                    void get_bits(void * num, char * out, int bytes);

                    int main(void)
                    {
                    int x = 0;

                    printf("Enter an integer: ");
                    scanf("%i", &x);

                    char bits[65] = {0};
                    get_bits(&x, bits, 4);

                    printf("%d in binary %sn", x, bits);

                    return 0;
                    }

                    //assumes char array of length 1 greater than
                    //number of bits

                    void get_bits(void * num, char *out, int bytes)
                    {
                    unsigned long long filter = 0x8000000000000000;
                    unsigned long long temp;

                    if(bytes <= 0) return;
                    if(bytes > 8) bytes = 8;

                    filter = filter >> (8*(sizeof(unsigned long long)-bytes));
                    memcpy(&temp, num, bytes);
                    int bits = 8*bytes;
                    for(int i=0;i<bits;i++) {
                    if(filter & temp)
                    out[i] = '1';
                    else
                    out[i] = '0';

                    temp = temp << 1;
                    }
                    out[bits] = '';
                    }


                    EDIT



                    Sorry, I just realized what Code Review meant. I figured I was suggesting an improvement, but I see how it did not match the intent here. Maybe this is closer.



                    Improvements



                    The posted code requires several loops, divisions, and modulus calculations. While it does solve the problem of representing an integer in binary, the utility may be limited by additional clock cycles.



                    The code may be optimized and extended to use with other integer representations, including char, short, or long long (or long depending on the size of long).



                    One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.



                    Alternative Solution



                    The function get_bits will accept any integer representation (presumably floating-point numbers as well, though I have not used it for this and not tested it).



                    It will "return," really populate, a character array with up to a 64-bit bit representation of the number.



                    It does rely on memcpy from string.h.



                    Inputs for get_bits



                    void *num : a pointer to the memory address of the number to be represented in
                    binary



                    char *out : the address of a character array to store the bit representation.

                    NOTE: This should be of length 1 longer than the number of bits to
                    be represented



                    int bytes : number of bytes containing the number to represent in binary



                    Implementation



                    Based on the size of the data type of the number to be represented, a mask is established with the highest bit set. This is the variable, filter, of type unsigned long long contained in 64-bits. Using bit shifting, a time requirement of 1 clock cycle, the filter is shifted to the right to align it with the highest bit of the number.



                    Ex. In hexadecimal, a 16-bit filter would be 0x8000, which in binary is 100000000000000.



                    The number is copied to a 64-bit block of memory, temp. After using memcpy of the standard c library, only a single for loop is performed to populate the output string. In each iteration of the loop, a bit-wise AND is performed with filter and temp. The result of this expression is either 0 or non-zero. The result is 0 only, when the highest order bit of temp is 0. The position in the output string is set to 1 if non-zero or 0 otherwise.



                    At the end of each iteration the temp is shifted by 1 bit to the left.



                    Ex. In binary, if temp is 1010, then temp << 1 is 0100. (a suitable filter would be 1000 in binary)






                    share|improve this answer










                    New contributor




                    RJM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.


















                    • Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
                      – Sᴀᴍ Onᴇᴌᴀ
                      3 hours ago
















                    0














                    #include stdio.h
                    #include string.h

                    void get_bits(void * num, char * out, int bytes);

                    int main(void)
                    {
                    int x = 0;

                    printf("Enter an integer: ");
                    scanf("%i", &x);

                    char bits[65] = {0};
                    get_bits(&x, bits, 4);

                    printf("%d in binary %sn", x, bits);

                    return 0;
                    }

                    //assumes char array of length 1 greater than
                    //number of bits

                    void get_bits(void * num, char *out, int bytes)
                    {
                    unsigned long long filter = 0x8000000000000000;
                    unsigned long long temp;

                    if(bytes <= 0) return;
                    if(bytes > 8) bytes = 8;

                    filter = filter >> (8*(sizeof(unsigned long long)-bytes));
                    memcpy(&temp, num, bytes);
                    int bits = 8*bytes;
                    for(int i=0;i<bits;i++) {
                    if(filter & temp)
                    out[i] = '1';
                    else
                    out[i] = '0';

                    temp = temp << 1;
                    }
                    out[bits] = '';
                    }


                    EDIT



                    Sorry, I just realized what Code Review meant. I figured I was suggesting an improvement, but I see how it did not match the intent here. Maybe this is closer.



                    Improvements



                    The posted code requires several loops, divisions, and modulus calculations. While it does solve the problem of representing an integer in binary, the utility may be limited by additional clock cycles.



                    The code may be optimized and extended to use with other integer representations, including char, short, or long long (or long depending on the size of long).



                    One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.



                    Alternative Solution



                    The function get_bits will accept any integer representation (presumably floating-point numbers as well, though I have not used it for this and not tested it).



                    It will "return," really populate, a character array with up to a 64-bit bit representation of the number.



                    It does rely on memcpy from string.h.



                    Inputs for get_bits



                    void *num : a pointer to the memory address of the number to be represented in
                    binary



                    char *out : the address of a character array to store the bit representation.

                    NOTE: This should be of length 1 longer than the number of bits to
                    be represented



                    int bytes : number of bytes containing the number to represent in binary



                    Implementation



                    Based on the size of the data type of the number to be represented, a mask is established with the highest bit set. This is the variable, filter, of type unsigned long long contained in 64-bits. Using bit shifting, a time requirement of 1 clock cycle, the filter is shifted to the right to align it with the highest bit of the number.



                    Ex. In hexadecimal, a 16-bit filter would be 0x8000, which in binary is 100000000000000.



                    The number is copied to a 64-bit block of memory, temp. After using memcpy of the standard c library, only a single for loop is performed to populate the output string. In each iteration of the loop, a bit-wise AND is performed with filter and temp. The result of this expression is either 0 or non-zero. The result is 0 only, when the highest order bit of temp is 0. The position in the output string is set to 1 if non-zero or 0 otherwise.



                    At the end of each iteration the temp is shifted by 1 bit to the left.



                    Ex. In binary, if temp is 1010, then temp << 1 is 0100. (a suitable filter would be 1000 in binary)






                    share|improve this answer










                    New contributor




                    RJM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.


















                    • Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
                      – Sᴀᴍ Onᴇᴌᴀ
                      3 hours ago














                    0












                    0








                    0






                    #include stdio.h
                    #include string.h

                    void get_bits(void * num, char * out, int bytes);

                    int main(void)
                    {
                    int x = 0;

                    printf("Enter an integer: ");
                    scanf("%i", &x);

                    char bits[65] = {0};
                    get_bits(&x, bits, 4);

                    printf("%d in binary %sn", x, bits);

                    return 0;
                    }

                    //assumes char array of length 1 greater than
                    //number of bits

                    void get_bits(void * num, char *out, int bytes)
                    {
                    unsigned long long filter = 0x8000000000000000;
                    unsigned long long temp;

                    if(bytes <= 0) return;
                    if(bytes > 8) bytes = 8;

                    filter = filter >> (8*(sizeof(unsigned long long)-bytes));
                    memcpy(&temp, num, bytes);
                    int bits = 8*bytes;
                    for(int i=0;i<bits;i++) {
                    if(filter & temp)
                    out[i] = '1';
                    else
                    out[i] = '0';

                    temp = temp << 1;
                    }
                    out[bits] = '';
                    }


                    EDIT



                    Sorry, I just realized what Code Review meant. I figured I was suggesting an improvement, but I see how it did not match the intent here. Maybe this is closer.



                    Improvements



                    The posted code requires several loops, divisions, and modulus calculations. While it does solve the problem of representing an integer in binary, the utility may be limited by additional clock cycles.



                    The code may be optimized and extended to use with other integer representations, including char, short, or long long (or long depending on the size of long).



                    One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.



                    Alternative Solution



                    The function get_bits will accept any integer representation (presumably floating-point numbers as well, though I have not used it for this and not tested it).



                    It will "return," really populate, a character array with up to a 64-bit bit representation of the number.



                    It does rely on memcpy from string.h.



                    Inputs for get_bits



                    void *num : a pointer to the memory address of the number to be represented in
                    binary



                    char *out : the address of a character array to store the bit representation.

                    NOTE: This should be of length 1 longer than the number of bits to
                    be represented



                    int bytes : number of bytes containing the number to represent in binary



                    Implementation



                    Based on the size of the data type of the number to be represented, a mask is established with the highest bit set. This is the variable, filter, of type unsigned long long contained in 64-bits. Using bit shifting, a time requirement of 1 clock cycle, the filter is shifted to the right to align it with the highest bit of the number.



                    Ex. In hexadecimal, a 16-bit filter would be 0x8000, which in binary is 100000000000000.



                    The number is copied to a 64-bit block of memory, temp. After using memcpy of the standard c library, only a single for loop is performed to populate the output string. In each iteration of the loop, a bit-wise AND is performed with filter and temp. The result of this expression is either 0 or non-zero. The result is 0 only, when the highest order bit of temp is 0. The position in the output string is set to 1 if non-zero or 0 otherwise.



                    At the end of each iteration the temp is shifted by 1 bit to the left.



                    Ex. In binary, if temp is 1010, then temp << 1 is 0100. (a suitable filter would be 1000 in binary)






                    share|improve this answer










                    New contributor




                    RJM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.









                    #include stdio.h
                    #include string.h

                    void get_bits(void * num, char * out, int bytes);

                    int main(void)
                    {
                    int x = 0;

                    printf("Enter an integer: ");
                    scanf("%i", &x);

                    char bits[65] = {0};
                    get_bits(&x, bits, 4);

                    printf("%d in binary %sn", x, bits);

                    return 0;
                    }

                    //assumes char array of length 1 greater than
                    //number of bits

                    void get_bits(void * num, char *out, int bytes)
                    {
                    unsigned long long filter = 0x8000000000000000;
                    unsigned long long temp;

                    if(bytes <= 0) return;
                    if(bytes > 8) bytes = 8;

                    filter = filter >> (8*(sizeof(unsigned long long)-bytes));
                    memcpy(&temp, num, bytes);
                    int bits = 8*bytes;
                    for(int i=0;i<bits;i++) {
                    if(filter & temp)
                    out[i] = '1';
                    else
                    out[i] = '0';

                    temp = temp << 1;
                    }
                    out[bits] = '';
                    }


                    EDIT



                    Sorry, I just realized what Code Review meant. I figured I was suggesting an improvement, but I see how it did not match the intent here. Maybe this is closer.



                    Improvements



                    The posted code requires several loops, divisions, and modulus calculations. While it does solve the problem of representing an integer in binary, the utility may be limited by additional clock cycles.



                    The code may be optimized and extended to use with other integer representations, including char, short, or long long (or long depending on the size of long).



                    One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.



                    Alternative Solution



                    The function get_bits will accept any integer representation (presumably floating-point numbers as well, though I have not used it for this and not tested it).



                    It will "return," really populate, a character array with up to a 64-bit bit representation of the number.



                    It does rely on memcpy from string.h.



                    Inputs for get_bits



                    void *num : a pointer to the memory address of the number to be represented in
                    binary



                    char *out : the address of a character array to store the bit representation.

                    NOTE: This should be of length 1 longer than the number of bits to
                    be represented



                    int bytes : number of bytes containing the number to represent in binary



                    Implementation



                    Based on the size of the data type of the number to be represented, a mask is established with the highest bit set. This is the variable, filter, of type unsigned long long contained in 64-bits. Using bit shifting, a time requirement of 1 clock cycle, the filter is shifted to the right to align it with the highest bit of the number.



                    Ex. In hexadecimal, a 16-bit filter would be 0x8000, which in binary is 100000000000000.



                    The number is copied to a 64-bit block of memory, temp. After using memcpy of the standard c library, only a single for loop is performed to populate the output string. In each iteration of the loop, a bit-wise AND is performed with filter and temp. The result of this expression is either 0 or non-zero. The result is 0 only, when the highest order bit of temp is 0. The position in the output string is set to 1 if non-zero or 0 otherwise.



                    At the end of each iteration the temp is shifted by 1 bit to the left.



                    Ex. In binary, if temp is 1010, then temp << 1 is 0100. (a suitable filter would be 1000 in binary)







                    share|improve this answer










                    New contributor




                    RJM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.









                    share|improve this answer



                    share|improve this answer








                    edited 9 mins ago





















                    New contributor




                    RJM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.









                    answered 4 hours ago









                    RJM

                    1093




                    1093




                    New contributor




                    RJM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.





                    New contributor





                    RJM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.






                    RJM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.












                    • Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
                      – Sᴀᴍ Onᴇᴌᴀ
                      3 hours ago


















                    • Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
                      – Sᴀᴍ Onᴇᴌᴀ
                      3 hours ago
















                    Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
                    – Sᴀᴍ Onᴇᴌᴀ
                    3 hours ago




                    Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
                    – Sᴀᴍ Onᴇᴌᴀ
                    3 hours ago










                    Vengeancos is a new contributor. Be nice, and check out our Code of Conduct.










                    draft saved

                    draft discarded


















                    Vengeancos is a new contributor. Be nice, and check out our Code of Conduct.













                    Vengeancos is a new contributor. Be nice, and check out our Code of Conduct.












                    Vengeancos is a new contributor. Be nice, and check out our Code of Conduct.
















                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210909%2fconvert-decimal-to-binary%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    What visual should I use to simply compare current year value vs last year in Power BI desktop

                    Alexandru Averescu

                    Trompette piccolo