Wednesday, July 20, 2011

Design a function getBits that gives x bits from a given position p of a given number n.

Approach

So we need mask for any bit set (10010011 etc). you want to generate a "mask" that pulls only the bits you want to see. So 10010011 or 0x03, I'm interested in xxxxx011. What is the mask that will extract that set ? 00000111 Now I want to be sizeof int independent, I'll let the machine do the work i.e. start with 0 for a byte machine it's 0x00 for a word machine it's 0x0000 etc. 64 bit machine would represent by 64 bits or 0x0000000000000000

Algorithm

Now apply "not" (~0) and get 11111111
shift right (<<) by n and get 11111000 and "not" that and get 00000111 it can be written as ~( ~ 0 << x )........(1) Okay we got our mask. 1. Now, we push the bits we want out of the number into the lowest order bits so we shift binary n by p+1-x ------(2) e.g. n >> p+1-x because so it's just a clever way to get n 1-bits in the least significant part of the number.

The "x bit" you describe has shifted the given number n right far enough so that the least significant x bits are the ones you want

take the and operation of above two you will that the number represented by that x bits or we can also return the bits if save that in to string or array

so we have to finally return ( ( n >> p+1-x ) & ~( ~ 0 << x )) so Here is Working Code for the same #include

unsigned int getbits(unsigned int x, int p, int n)
{
return (x >> (p + 1 - n)) & ~(~0 << n);
}
int main(void) {
int x = 182, p = 2, n = 5;
int z = getbits(x, p, n);
printf("getbits(%u (%x), %d, %d) = %u (%X)\n", x, x, p, n, z, z);
//% u for unsigned & %x for hexadecimal numbers


return 0;
}

Time Complexity O(1)
Space Complexity O(1)
Run Here https://ideone.com/eglaQ

No comments :