Answers:
This is the code for any bit compiler... #define TESTBIT 1 /*always better to represent like this instead of the code written above.... or place a constant before test bit so that no changes can be made....*/ int no_of_1s=0; for(i=0; i < (sizeof(int) * 8) ; i++) { if(given_no & (TESTBIT<<i) no_of_1s++; }
//for 16-bit no // int no_of_1s=0; int testbit=1; for(i=0;i<16;i++) { if(given_no&testbit) no_of_1s++; testbit = testbit<<1; } //now the variable no_of_1s is having the result
Posted by: subbiah
Contact subbiah
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
There should not be any Spelling Mistakes.
There should not be any Gramatical Errors.
Answers must not contain any bad words.
Answers should not be the repeat of same answer, already approved.
Answer should be complete in itself.