I had a interview today where they asked me to write two "C" functions, one to to extract a single bit and other to extract a range of bits from a character. I took a while and came up with these methods.
int extractBit(char byte, int pos) {
assert( (pos >= 0) && (pos < 8) );
return ( ( byte & (1<<pos) ) >> pos);
}
char extractBitRange(char byte, int startingPos, int offset) {
assert( ( (startingPos + offset) >= 0) && ( (startingPos + offset) < 8) );
return ( byte >> startingPos ) & ~(0xff << (offset + 1));
}
But the interviewer kept asking me if I could speed up the code further (in terms of cpu cycles) and if there is any scope of optimization that I could do to achieve it. I was clearly out of sorts and I am curious to know how would you do this?