Interesting interview question yesterday

So interviewer says "I want you to write out a short function to read in 1 byte and put out how many bits are in it". Thoroughly confused I ask him to repeat. "I want it to read in 1 byte, and pull out each bit individually". I had to claim ignorance at this point.

This was yesterday in a long interview, so it's not verbatim - but pretty close

What am I missing here?
What am I missing here?

The solution, I guess?
What are you trying to say?
In C++, a byte is a char. As for how many bits are in it; that's system dependent. Fortunately, if you've got a conformant implementation, you can use the climits header to know how many bits there are in the byte, and then you can determine the value of each bit (one or zero) by bit-masking or bitshifting or whatever your preferred method is.
thx Moschops
I got that he was alluding to a char, but as for reading the individual bits, I never even considered that was something that anyone would want to do.
It's quite common in C++; I see it a lot in flag bitsets indicating the status of objects. For example, checking the state of a stream. You've probably set flags and read flags without realising it.
I don't know if that's what he asked (the question sounds kinda confusing, maybe you just misunderstood him):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
#include <climits>


std::string getBits(char c);

int main(int argc, char** argv) {
	for(int i=1; i<argc; ++i)
	{
		std::string str = argv[i];
		for(auto it = str.begin(); it!=str.end(); ++it)
		{
			std::cout<<getBits(*it)<<" ";
		}
		std::cout<<std::endl;
	}
	return 0;
}

std::string getBits(char c)
{
	std::string result;
	for(int i=0, bitVal=1; i<CHAR_BIT; ++i)
	{
		if(c & bitVal)
		{
			result.push_back('1');
			c-=bitVal;
		} else {
			result.push_back('0');
		}
		bitVal<<=1;
	}
	return std::string(result.rbegin(), result.rend());
}


arguments: hello world
01101000 01100101 01101100 01101100 01101111 
01110111 01101111 01110010 01101100 01100100 
Last edited on
Interviewers often know less about the language than you do -- they go wandering in with a list of questions to (mis-)ask.

The interviewer was probably trying to ask for a function that calculates the number of set bits in a byte. This is a very old problem, with quite a number of well-known solutions.

http://graphics.stanford.edu/~seander/bithacks.html (See "Counting Bits Set")
http://gurmeet.net/puzzles/fast-bit-counting-routines/

There are others, but that's it for now...
Topic archived. No new replies allowed.