Need help understanding “getbits()” method in Chapter 2 of K&R C

后端 未结 6 1076
暗喜
暗喜 2020-12-04 16:03

In chapter 2, the section on bitwise operators (section 2.9), I\'m having trouble understanding how one of the sample methods works.

Here\'s the method provided:

6条回答
  •  一向
    一向 (楼主)
    2020-12-04 16:35

    I would say the best thing to do is to do a problem out by hand, that way you'll understand how it works.

    Here is what I did using an 8-bit unsigned int.

    1. Our number is 75 we want the 4 bits starting from position 6. the call for the function would be getbits(75,6,4);

    2. 75 in binary is 0100 1011

    3. So we create a mask that is 4 bits long starting with the lowest order bit this is done as such.

    ~0 = 1111 1111
    <<4 = 1111 0000
    ~ = 0000 1111

    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 75 by 6+1-4=3.

    0100 1011 >>3 0000 1001

    Now we have a mask of the correct number of bits in the low order and the bits we want out of the original number in the low order.

    1. so we & them
      0000 1001 
    & 0000 1111 ============ 0000 1001

    so the answer is decimal 9.

    Note: the higher order nibble just happens to be all zeros, making the masking redundant in this case but it could have been anything depending on the value of the number we started with.

提交回复
热议问题