Converting an integer to binary in C

后端 未结 12 1229
别跟我提以往
别跟我提以往 2021-02-02 04:30

I\'m trying to convert an integer 10 into the binary number 1010.

This code attempts it, but I get a segfault on the strcat():

int int_to_bin(int k)
{
          


        
12条回答
  •  轮回少年
    2021-02-02 04:39

    Result in string

    The following function converts an integer to binary in a string (n is the number of bits):

    // Convert an integer to binary (in a string)
    void int2bin(unsigned integer, char* binary, int n=8)
    {  
      for (int i=0;i

    Test online on repl.it.

    Source : AnsWiki.

    Result in string with memory allocation

    The following function converts an integer to binary in a string and allocate memory for the string (n is the number of bits):

    // Convert an integer to binary (in a string)
    char* int2bin(unsigned integer, int n=8)
    {
      char* binary = (char*)malloc(n+1);
      for (int i=0;i

    This option allows you to write something like printf ("%s", int2bin(78)); but be careful, memory allocated for the string must be free later.

    Test online on repl.it.

    Source : AnsWiki.

    Result in unsigned int

    The following function converts an integer to binary in another integer (8 bits maximum):

    // Convert an integer to binary (in an unsigned)
    unsigned int int_to_int(unsigned int k) {
        return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
    }
    

    Test online on repl.it

    Display result

    The following function displays the binary conversion

    // Convert an integer to binary and display the result
    void int2bin(unsigned integer, int n=8)
    {  
      for (int i=0;i

    Test online on repl.it.

    Source : AnsWiki.

提交回复
热议问题