decimal number convert to 16bit binary (C)

I want to convert a decimal number to a 16 bit binary number.
My code does not work at all but I am sure that I did the right steps.
Hope for some help.

#include <stdio.h>
#include <stdlib.h>

const int BIT = 16;

char binaer(int i) {
    char str[BIT];
    int j = 0;
    if(0 <= i && i <= 65535) {
        for(int j = 0; j < BIT + 1; j++) {
            if (i % 2 == 0) {
                str[j] = '0';
            } else {
                str[j] = '1';
            }
            i = i / 2;
        }
    }
    for(int x = BIT - 1; x >= 0; x--){
       printf("%c", str[x]);
    }
}

int main() {

    int value;
    scanf("%d", &value);
    binaer(value);


    return 0;
}

Input: 16
Output: 00001000000000000

1 answer

  • answered 2018-01-13 17:38 coderredoc

    First of all the loop in main() is meaningless. Call the function once and it's done.

    str is a 16 element char array whose elements can be accessed via indices 0 to 15. You accessed the 16th one resulting in Undefined behavior.

    %s in printf expects a null terminated char array. You didn't provide. That's Undefined Behavior again.

    The function doesn't return anything. Make the return type void.

    Inversely printing the binary form is being done. Make sure this is what you want. You should print the array in reverse. After the for loop is done you will print it.

    for(int in = BIT-1; in >= 0; in--){
        printf("%c",str[in]);
    }
    printf("\n");
    

    The way I printed it, if followed, the null terminator is not needed.