Converting decimal number to binary in C

前端 未结 4 1779
日久生厌
日久生厌 2021-01-17 03:22

I\'m trying to convert a decimal number to binary but I somehow end up getting \'random\' ASCII symbols as an output. Here is my program:

#include 

        
4条回答
  •  迷失自我
    2021-01-17 03:50

    You are filling in your array from the back to the front. You stop once the number is "done", and don't "left pad" the remaining characters at the start of the array so they are not initialized. Either initialize the whole array to '0' at the start, or add something like:

    while(i >= 0) {
        binary[i] = '0';
        i--;
    }
    

    at the end. (I think I'd got with initializing to '0'). You also need to ensure that buffer is big enough (50, not 10). And insert chars, not ints: binary[i] = '0' + (number % 2);

提交回复
热议问题