Converting an integer to binary in C

后端 未结 12 1247
别跟我提以往
别跟我提以往 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:37

    If you want to transform a number into another number (not number to string of characters), and you can do with a small range (0 to 1023 for implementations with 32-bit integers), you don't need to add char* to the solution

    unsigned int_to_int(unsigned k) {
        if (k == 0) return 0;
        if (k == 1) return 1;                       /* optional */
        return (k % 2) + 10 * int_to_int(k / 2);
    }
    

    HalosGhost suggested to compact the code into a single line

    unsigned int int_to_int(unsigned int k) {
        return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
    }
    

提交回复
热议问题