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

后端 未结 6 1084
暗喜
暗喜 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:25

    Using the example: int x = 0xF994, p = 4, n = 3; int z = getbits(x, p, n);

    and focusing on this set of operations ~(~0 << n)

    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

    Now apply "not" (~0) and get 11111111
    shift right (<<) by n and get 11111000
    and "not" that and get 00000111

    so 10010011 & 00000111 = 00000011
    You remember how boolean operations work ?

提交回复
热议问题