Pergunta de entrevista da empresa Microsoft

Count bits in a byte.

Respostas da entrevista

Sigiloso

21 de nov. de 2009

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

1

Sigiloso

12 de ago. de 2011

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

Sigiloso

1 de out. de 2011

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

Sigiloso

6 de mai. de 2009

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

Sigiloso

30 de mai. de 2009

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

Sigiloso

9 de jul. de 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; }

Sigiloso

17 de out. de 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?

Sigiloso

17 de out. de 2009

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

Sigiloso

30 de mai. de 2009

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

Sigiloso

5 de mai. de 2009

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