Converting an integer to binary in C

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

    You can convert decimal to bin, hexa to decimal, hexa to bin, vice-versa etc by following this example. CONVERTING DECIMAL TO BIN

    int convert_to_bin(int number){
        int binary = 0, counter = 0;
        while(number > 0){
            int remainder = number % 2;
            number /= 2;
            binary += pow(10, counter) * remainder;
            counter++;
        }   
    }
    

    Then you can print binary equivalent like this:

    printf("08%d", convert_to_bin(13)); //shows leading zeros

提交回复
热议问题