Thread: help me to write this function ^^

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    2

    Question 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. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    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

    Hope this will help you.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  2. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Replies: 5
    Last Post: 02-08-2003, 07:42 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM