Converting an integer to binary in C

后端 未结 12 1248
别跟我提以往
别跟我提以往 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条回答
  •  Happy的楠姐
    2021-02-02 04:49

    You can use function this function to return char* with string representation of the integer:

       char* itob(int i) {
          static char bits[8] = {'0','0','0','0','0','0','0','0'};
          int bits_index = 7;
          while ( i > 0 ) {
             bits[bits_index--] = (i & 1) + '0';
             i = ( i >> 1);
          }
          return bits;
       }
    

    It's not a perfect implementation, but if you test with a simple printf("%s", itob(170)), you'll get 01010101 as I recall 170 was. Add atoi(itob(170)) and you'll get the integer but it's definitely not 170 in integer value.

提交回复
热议问题