tags:

views:

65

answers:

6

Hey guys

Jus check out this program.Logically it seems fine but its giving 000000000000000000000 for everything

#include<stdio.h>
void main()
{
int n=25,k=32;
printf("binary equivalent\n");
while(k!=0)
{
 if((n>>1&0x01)!=0)
  printf("1");
 else
  printf("0");
 k--;
}
}
+7  A: 

You don't ever change n.

Don't try and cram everything into one line, be a little more verbose so that things are clearer.

while(k!=0)
{
 if((n & 0x01) != 0)
  printf("1");
 else
  printf("0");
 k--;
 n >>= 1;
}
Anon.
oops... realised my error! forgot to modify the value of n! thanks..
Ram Bhat
That's going to print the binary digits in reverse order...
caf
+4  A: 
falagar
+1  A: 

You are not modifying n - every time you compare 0x01 with second bit on n.

qrdl
+1  A: 

You don't change the value of n within the loop. And probably you want to test the least significant bit before shifting.

stacker
+2  A: 

Your n is never getting changed:

if((n>>1&0x01)!=0)

should be

if(n & 0x01)

and add

n>>=1; after k--;

Also this will produce the binary representation in reverse order.

codaddict
+1  A: 

i think it will help the result is the same as other poster posted

#include<stdio.h>
void main()
{
int n=25;
int k=32;
printf("binary equivalent\n");

 for (int i=0;i<32;i++){
 if((n&1)!=0)
  printf("1");
 else
  printf("0");

 n>>=1;
 }


}

as @falagar said result will be printed in reverse order