Converting an integer to binary in C

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

    You can add the functions to the standard library and use it whenever you need.

    Here is the code in C++

    #include 
    
    int power(int x, int y) //calculates x^y.
    {
    int product = 1;
    for (int i = 0; i < y; i++)
    {
        product = product * x;
    }
    return (product);
    }
    int gpow_bin(int a) //highest power of 2 less/equal to than number itself.
    {
    int i, z, t;
    for (i = 0;; i++)
    {
        t = power(2, i);
        z = a / t;
        if (z == 0)
        {
            break;
        }
    }
    return (i - 1);
    }
    void bin_write(int x)
    {
    //printf("%d", 1);
    int current_power = gpow_bin(x);
    int left = x - power(2, current_power);
    int lower_power = gpow_bin(left);
    for (int i = 1; i < current_power - lower_power; i++)
    {
        printf("0");
    }
    if (left != 0)
    {
        printf("%d", 1);
        bin_write(left);
    }
    }
    void main()
    {
    //printf("%d", gpow_bin(67));
    int user_input;
    printf("Give the input:: ");
    scanf("%d", &user_input);
    printf("%d", 1);
    bin_write(user_input);
    }
    

提交回复
热议问题