Convert decimal to binary












3














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.

























    3














    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.























      3












      3








      3







      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 4 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 4 hours ago









      Vengeancos

      564




      564




      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


















          3














          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] = '';
            }


            The code above stores characters representing the bits for char, short, int, or long long in a character array (up to 64 bits). It does not require reversing the order of bits and restoring them. Essentially, it creates a mask ("filter") with a single bit set. This is always the highest order bit. initially, it is the highest order bit for a 64 bit number. For a 32-bit integer, the mask will be shifted to have the 32 bit set, all others 0. The mask will be adjusted for whatever number of bytes the caller indicates are in the number.



            A logical and is performed with the number. If the corresponding bit is 1 in the number, it stores a 1 character in the array passed to get_bits. The number, temporarily stored in the variable, temp, is shifted left in each iteration of the for loop. This allows comparison each iteration of the highest order bit in the number. If it is not set in the number, filter & temp is 0 and a 0 character is stored at that position in the output string.



            The user of the function get_bits must pass a void pointer, which stores the address of the number, for which the bits are determined. The argument out is a pointer to a character array for the output string. This should be one character longer than the number of bits in the number. The argument bytes represents the bytes of data required to store the number. The output character array is null terminated at position corresponding to the number of bits in the number (that is the length of the string with null terminator is one greater than the number of bytes *8).






            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ᴇᴌᴀ
              1 hour ago










            • @SᴀᴍOnᴇᴌᴀ Thanks. New on this site. I was having trouble just editing the code. I will put it in.
              – RJM
              1 hour ago










            • @SᴀᴍOnᴇᴌᴀ So, different than Math Stack Exchange, it seems we should not put up alternatives. Is that so? I thought my answer was so different, that it provides extended understanding of how to answer.
              – RJM
              1 hour 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









            3














            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


























              3














              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
























                3












                3








                3






                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 4 hours ago









                Reinderien

                3,733721




                3,733721

























                    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] = '';
                    }


                    The code above stores characters representing the bits for char, short, int, or long long in a character array (up to 64 bits). It does not require reversing the order of bits and restoring them. Essentially, it creates a mask ("filter") with a single bit set. This is always the highest order bit. initially, it is the highest order bit for a 64 bit number. For a 32-bit integer, the mask will be shifted to have the 32 bit set, all others 0. The mask will be adjusted for whatever number of bytes the caller indicates are in the number.



                    A logical and is performed with the number. If the corresponding bit is 1 in the number, it stores a 1 character in the array passed to get_bits. The number, temporarily stored in the variable, temp, is shifted left in each iteration of the for loop. This allows comparison each iteration of the highest order bit in the number. If it is not set in the number, filter & temp is 0 and a 0 character is stored at that position in the output string.



                    The user of the function get_bits must pass a void pointer, which stores the address of the number, for which the bits are determined. The argument out is a pointer to a character array for the output string. This should be one character longer than the number of bits in the number. The argument bytes represents the bytes of data required to store the number. The output character array is null terminated at position corresponding to the number of bits in the number (that is the length of the string with null terminator is one greater than the number of bytes *8).






                    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ᴇᴌᴀ
                      1 hour ago










                    • @SᴀᴍOnᴇᴌᴀ Thanks. New on this site. I was having trouble just editing the code. I will put it in.
                      – RJM
                      1 hour ago










                    • @SᴀᴍOnᴇᴌᴀ So, different than Math Stack Exchange, it seems we should not put up alternatives. Is that so? I thought my answer was so different, that it provides extended understanding of how to answer.
                      – RJM
                      1 hour 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] = '';
                    }


                    The code above stores characters representing the bits for char, short, int, or long long in a character array (up to 64 bits). It does not require reversing the order of bits and restoring them. Essentially, it creates a mask ("filter") with a single bit set. This is always the highest order bit. initially, it is the highest order bit for a 64 bit number. For a 32-bit integer, the mask will be shifted to have the 32 bit set, all others 0. The mask will be adjusted for whatever number of bytes the caller indicates are in the number.



                    A logical and is performed with the number. If the corresponding bit is 1 in the number, it stores a 1 character in the array passed to get_bits. The number, temporarily stored in the variable, temp, is shifted left in each iteration of the for loop. This allows comparison each iteration of the highest order bit in the number. If it is not set in the number, filter & temp is 0 and a 0 character is stored at that position in the output string.



                    The user of the function get_bits must pass a void pointer, which stores the address of the number, for which the bits are determined. The argument out is a pointer to a character array for the output string. This should be one character longer than the number of bits in the number. The argument bytes represents the bytes of data required to store the number. The output character array is null terminated at position corresponding to the number of bits in the number (that is the length of the string with null terminator is one greater than the number of bytes *8).






                    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ᴇᴌᴀ
                      1 hour ago










                    • @SᴀᴍOnᴇᴌᴀ Thanks. New on this site. I was having trouble just editing the code. I will put it in.
                      – RJM
                      1 hour ago










                    • @SᴀᴍOnᴇᴌᴀ So, different than Math Stack Exchange, it seems we should not put up alternatives. Is that so? I thought my answer was so different, that it provides extended understanding of how to answer.
                      – RJM
                      1 hour 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] = '';
                    }


                    The code above stores characters representing the bits for char, short, int, or long long in a character array (up to 64 bits). It does not require reversing the order of bits and restoring them. Essentially, it creates a mask ("filter") with a single bit set. This is always the highest order bit. initially, it is the highest order bit for a 64 bit number. For a 32-bit integer, the mask will be shifted to have the 32 bit set, all others 0. The mask will be adjusted for whatever number of bytes the caller indicates are in the number.



                    A logical and is performed with the number. If the corresponding bit is 1 in the number, it stores a 1 character in the array passed to get_bits. The number, temporarily stored in the variable, temp, is shifted left in each iteration of the for loop. This allows comparison each iteration of the highest order bit in the number. If it is not set in the number, filter & temp is 0 and a 0 character is stored at that position in the output string.



                    The user of the function get_bits must pass a void pointer, which stores the address of the number, for which the bits are determined. The argument out is a pointer to a character array for the output string. This should be one character longer than the number of bits in the number. The argument bytes represents the bytes of data required to store the number. The output character array is null terminated at position corresponding to the number of bits in the number (that is the length of the string with null terminator is one greater than the number of bytes *8).






                    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] = '';
                    }


                    The code above stores characters representing the bits for char, short, int, or long long in a character array (up to 64 bits). It does not require reversing the order of bits and restoring them. Essentially, it creates a mask ("filter") with a single bit set. This is always the highest order bit. initially, it is the highest order bit for a 64 bit number. For a 32-bit integer, the mask will be shifted to have the 32 bit set, all others 0. The mask will be adjusted for whatever number of bytes the caller indicates are in the number.



                    A logical and is performed with the number. If the corresponding bit is 1 in the number, it stores a 1 character in the array passed to get_bits. The number, temporarily stored in the variable, temp, is shifted left in each iteration of the for loop. This allows comparison each iteration of the highest order bit in the number. If it is not set in the number, filter & temp is 0 and a 0 character is stored at that position in the output string.



                    The user of the function get_bits must pass a void pointer, which stores the address of the number, for which the bits are determined. The argument out is a pointer to a character array for the output string. This should be one character longer than the number of bits in the number. The argument bytes represents the bytes of data required to store the number. The output character array is null terminated at position corresponding to the number of bits in the number (that is the length of the string with null terminator is one greater than the number of bytes *8).







                    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 1 hour 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 2 hours ago









                    RJM

                    1013




                    1013




                    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ᴇᴌᴀ
                      1 hour ago










                    • @SᴀᴍOnᴇᴌᴀ Thanks. New on this site. I was having trouble just editing the code. I will put it in.
                      – RJM
                      1 hour ago










                    • @SᴀᴍOnᴇᴌᴀ So, different than Math Stack Exchange, it seems we should not put up alternatives. Is that so? I thought my answer was so different, that it provides extended understanding of how to answer.
                      – RJM
                      1 hour 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ᴇᴌᴀ
                      1 hour ago










                    • @SᴀᴍOnᴇᴌᴀ Thanks. New on this site. I was having trouble just editing the code. I will put it in.
                      – RJM
                      1 hour ago










                    • @SᴀᴍOnᴇᴌᴀ So, different than Math Stack Exchange, it seems we should not put up alternatives. Is that so? I thought my answer was so different, that it provides extended understanding of how to answer.
                      – RJM
                      1 hour 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ᴇᴌᴀ
                    1 hour 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ᴇᴌᴀ
                    1 hour ago












                    @SᴀᴍOnᴇᴌᴀ Thanks. New on this site. I was having trouble just editing the code. I will put it in.
                    – RJM
                    1 hour ago




                    @SᴀᴍOnᴇᴌᴀ Thanks. New on this site. I was having trouble just editing the code. I will put it in.
                    – RJM
                    1 hour ago












                    @SᴀᴍOnᴇᴌᴀ So, different than Math Stack Exchange, it seems we should not put up alternatives. Is that so? I thought my answer was so different, that it provides extended understanding of how to answer.
                    – RJM
                    1 hour ago




                    @SᴀᴍOnᴇᴌᴀ So, different than Math Stack Exchange, it seems we should not put up alternatives. Is that so? I thought my answer was so different, that it provides extended understanding of how to answer.
                    – RJM
                    1 hour 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

                    Understanding the information contained in the Deep Space Network XML data?

                    Ross-on-Wye

                    Eastern Orthodox Church