Jong Sun Choi Jong Sun Choi - 24 days ago 14
C Question

negative decimal to binary c code

I can't write negative decimal to binary c code.
need help :)
Here is my code......
There is no need other includes.

#include <stdio.h>

int main(void){
int i;
int j;
int b[16];
printf("input number");
scanf("%d",&i);
if(i <= 0) {
// here is negative decimal code
} else {
for(j=15;j>=0;j--) {
b[j] = i % 2;
i = i / 2;
}
for (j=0;j<=15;j++)
printf("%d", b[j]);
printf("\n");
}
return 0;
}

Answer

You can use bitshift operator to get the bits.

#include <stdio.h>

    int main(void){
        int i;
        int j;
        int b[16]; //Assuming your integer size is 16bit
        printf("input number");
        scanf("%d",&i);

        for(j=15;j>=0;j--) {
            b[j] = i & 0x1;
            i = i >> 1;
        }

        for (j=0;j<=15;j++)
            printf("%d", b[j]);

        printf("\n");
        return 0;
    }
Comments