Converting an integer to binary in C

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

    Well, I had the same trouble ... so I found this thread

    I think the answer from user:"pmg" does not work always.

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

    Reason: the binary representation is stored as an integer. That is quite limited. Imagine converting a decimal to binary:

     dec 255  -> hex 0xFF  -> bin 0b1111_1111
     dec 1023 -> hex 0x3FF -> bin 0b11_1111_1111
    

    and you have to store this binary representation as it were a decimal number.

    I think the solution from Andy Finkenstadt is the closest to what you need

    unsigned int_to_int(unsigned int k) {
        char buffer[65]; // any number higher than sizeof(unsigned int)*bits_per_byte(8)
        return itoa( atoi(k, buffer, 2) );
    }
    

    but still this does not work for large numbers. No suprise, since you probably don't really need to convert the string back to decimal. It makes less sense. If you need a binary number usually you need for a text somewhere, so leave it in string format.

    simply use itoa()

    char buffer[65];
    itoa(k, buffer, 2);
    

提交回复
热议问题