Microsoft Interview Question

Count bits in a byte.

Interview Answers

Anonymous

Nov 21, 2009

Funny way: while (x != 0) { x = x& (x-1) count++; }

1

Anonymous

Aug 12, 2011

while (number > 0) { count += (number & 0x01); number >>= 1; }

Anonymous

Oct 1, 2011

Shifting may not work if the number has a sign bit... will keep pushing in ones. num&num-1 should work

Anonymous

May 6, 2009

byte input; int bits = 0; for(int i = 0; i > i) & 0x01; }

Anonymous

May 30, 2009

better solution: byte input; int count = 0; while (input) { ++count; input >> 1; }

Anonymous

Jul 9, 2009

The *ONLY* portable way to answer this question such that it is correct for *ALL* ANSI C compilers on *ALL* hardware platforms is as follows: #include #include int main() { printf("Number of bits per byte on this machine with this ANSI C compiler = %d\n", CHAR_BIT); return 0; }

Anonymous

Oct 17, 2009

i think the question was written wrong by the person i checked on google and the question is Count the "on" bits in a byte?

Anonymous

Oct 17, 2009

one way to solve this char c; int bits=0; for (int i=0;i>1; } return bits

Anonymous

May 30, 2009

better solution: byte input; int count = 0; while (input) { ++count; cout >> 1; }

Anonymous

May 5, 2009

Its 8 of course, but I WISH I had that question... lol