Converting an integer to binary in C

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

    void intToBin(int digit) {
        int b;
        int k = 0;
        char *bits;
    
        bits= (char *) malloc(sizeof(char));
        printf("intToBin\n");
        while (digit) {
            b = digit % 2;
            digit = digit / 2;
            bits[k] = b;
            k++;
    
            printf("%d", b);
        }
        printf("\n");
        for (int i = k - 1; i >= 0; i--) {
            printf("%d", bits[i]);
    
        }
    
    }
    

提交回复
热议问题