# help me to write this function ^^

This is a discussion on help me to write this function ^^ within the C Programming forums, part of the General Programming Boards category; I don't understand this question so please tell me how can I start to write. Write a funtion called bitpat_get ...

1. ## help me to write this function ^^

I don't understand this question so please tell me how can I start
to write.
Write a funtion called bitpat_get to extract a specified set of bits from an int variable. Assume the function takes three arguments: the first is an unsigned int from which the bits are extracted; the second is an int that is the position of starting bit; and the third is a bit count.
Using the convention that bit numbering starts at 0 with the leftmost bit, extract the specified number of bits from the first argument and put the extracted bits at the rightmost bits of an int variable which is returned from the function( The remaining bits of the returned variable should be 0's)
So the call y=bitpat_get(x,3,5);
will extract five bits from x sarting with the fourth bit from the left, and return the result to y.

2. Do you know bitshifting (>> <<) and bitwise operators (& | ^)?

What you are going to do is make a "mask" and then use it to extract the bits from the integer (assuming 16bit integers).

In your case, the mask will look like this (binary): 0001 1111 0000 0000. It starts on the fourth bit from the left.

Then you use bitwise and (&) on the integer and the mask:

1101 0110 1001 0101
0001 1111 0000 0000

0001 0110 0000 0000

And finally shift the bits so they appear at the rightmost position. If you look at the mask, you have 8 zero's to the right of the one's, so you shift the answer 8 steps to the right (using >>).

0000 0000 0001 0110