This site features a collection of common technical interview questions gathered by a group of programmers who have been through, and given, lots of technical interviews. There is an emphasis on C++ and game programming technical interviews, but most of the questions are relevant to any technical interview.
Bits ‘n Bytes

Write a function that returns the number of bits that are “on” (set to 1) in a byte. How can you make this function as fast as possible?

int countBits(unsigned char aByte)
{

1 Comment so far
Leave a comment

The idea is to bit-and with n-1. Every time this is done, the ’1′ on the LSB becomes 0.
Do this till the whole number becomes 0.

int count = 0;
while (n) { n = n&(n-1); count ++ }

return count;



Leave a comment
If you are including code in your comment, place it within a <div class='code'></div> tag for better formatting.


Do you have a technical interview question you would like to submit? Some tips you would like to pass on? Just want to say hi? Feel free to contact us