### Binary Representation of a Number

Below code is for Binary Representation of a Number.
This code works fine.....but i don't know why
if((x&(0x80000000))>0) should be <0 instead of >0
because if first bit of x is 1, number generated would be -2147483748 which is less than 0 but still this code works....

#include<stdio.h>
int main()
{
int x;
scanf("%d",&x);
for(int i=0;i<32;i++)
{
if((x&(0x80000000))>0)
printf("1");
else
printf("0");
x=x<<1;
}
printf("\n");
getchar();
getchar();
return 0;
}
Was as confused as you were also, so I went ahead and printed the values of x and the value of the & condition. Turns out the value of the condition results in an unsigned value therefore checking for `< 0;` would not have produced desired results

 ``12345678910111213141516171819`` ``````#include int main() { FILE* out = fopen("valueofx.txt", "w+"); int x; scanf("%d",&x); for(int i=0;i<32;i++) { if((x&(0x80000000))>0) putchar('1'); else putchar('0'); fprintf(out, "%d %u\n", x, (x&(0x80000000))); x=x<<1; } putchar('\n'); getchar(); return 0; }``````

Output:
 ```234534 0 469068 0 938136 0 1876272 0 3752544 0 7505088 0 15010176 0 30020352 0 60040704 0 120081408 0 240162816 0 480325632 0 960651264 0 1921302528 0 -452362240 2147483648 -904724480 2147483648 -1809448960 2147483648 676069376 0 1352138752 0 -1590689792 2147483648 1113587712 0 -2067791872 2147483648 159383552 0 318767104 0 637534208 0 1275068416 0 -1744830464 2147483648 805306368 0 1610612736 0 -1073741824 2147483648 -2147483648 2147483648 0 0```

And here is the value 234534 converted to binary:
00000000000000111001010000100110

Notice how the 1's match up with the places where 2147483648 appears in the output?
Last edited on
Topic archived. No new replies allowed.