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?
*/ Step 1 : first convert the number into its binary form using bin(). Step 2 : remove the first two character. Step 3 : then extracting k bits from starting position pos from right.so, the ending index of the extracting substring is e=len(bi)-pos and starting index=e-k+1 Step 4 : extract k bit sub-string.
How to extract 'k' bits from a given position 'p' in a number? Examples: Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21.
8 bits = 1 byte. 1,024 bytes = kilobyte. 1,024 kilobytes = megabyte.
Logic to get nth bit of a number Input the bit position from user. Store it in some variable say n . To get the nth bit of num right shift num , n times. Then perform bitwise AND with 1 i.e. bitStatus = (num >> n) & 1; .
In extractBit, if you shift first, you can mask with 1
instead of (1<<pos)
.
Considering that pos is an argument of the function, that saves a computation.
return (byte >> pos) & 1;
In the second function, I would assert that startingPos
and offset
are both positive instead of asserting that their sum is positive, it makes more sense that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With