Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract a bit in a more optimal way?

Tags:

c

optimization

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?

like image 226
rajachan Avatar asked Oct 04 '09 12:10

rajachan


People also ask

How do I extract a bit in Python?

*/ 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 do you extract K bits from a given position P in a number?

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.

How do you read a byte from a bit?

8 bits = 1 byte. 1,024 bytes = kilobyte. 1,024 kilobytes = megabyte.

How do you find the N bit of a number?

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; .


1 Answers

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.

like image 60
Pascal Cuoq Avatar answered Sep 17 '22 13:09

Pascal Cuoq