简体   繁体   中英

Why can't i get the right output in decimal to binary conversion?

printf("Enter a positive integer");
unsigned int ip;
scanf("%d", &ip);
printf("\n Binary Conversion: ");
int c,k,count = 1;
for(c = 31; c >= 0; c--) {
    k = ip >> c;
    if(k && 1) {
        printf("1");
    } else {
        printf("0");
    }

    if(count % 8 == 0) {
        printf(" ");
    }
     count++;
}

For some reason it doesn't give me the correct output even if i remove the unassign also.

Your problem is on this line:

if(k && 1)

&& is the logical AND operator, not the bitwise AND operator you need to be using. What it is testing is "if k and 1 are both non-zero, proceed", and the 1 is obviously redundant, so it's testing "if k is not zero, proceed", which will make that statement true in a lot of cases where you don't want to be printing a 1 .

The line should be written as:

if(k & 1)

You can even shorten your code to:

#include <stdio.h>

int main()
{
    unsigned int ip;
    int i;
    printf("Enter a positive integer: ");
    scanf("%d", &ip);
    printf("\nBinary Conversion: ");
    for(i = 31; i >= 0; i--)
    {
        printf("%d", (ip>>i)&1);    
        if(i%8==0) printf(" ");
    }
    return 0;
}

To avoid using if / else altogether.

Instead of using %d you should use %u. Use & instead of &&

printf("Enter a positive integer");
unsigned int ip;
scanf("%u", &ip);
printf("\n Binary Conversion: ");
int c,k,count = 1;
for(c = 31; c >= 0; c--) {
    k = ip >> c;
    if(k & 1) {
        printf("1");
    } else {
        printf("0");
    }

    if(count % 8 == 0) {
        printf(" ");
    }
     count++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM