What is the significance of these #defines?

泪湿孤枕 提交于 2019-12-25 01:42:54

问题


I was going through the best solution of problem MAXCOUNT and found few lines which i didn't understand.

Codechef Problem and the Best Solution submitted

While I was reading the code to observe the approach, I encountered these lines at the top of code:

#define isSet(n) flags[n>>5]&(1<<(n&31))
#define unset(n) flags[n>>5] &= ~(1<<(n&31))
#define set(n) flags[n>>5]|=(1<<(n&31))

I have no idea what is the significance of using these lines.
Can anyone please explain these lines and why are they used?


回答1:


It looks like it is referring to an array of bits stored as integers. n >> 5 means divide it by 32, and there's 32 bits in an int so that indexes the array. Then the right hand side uses the remainder (the bit pattern of 31 is is 0b11111 meaning the and operation with it will filter out all the rest of the bits, leaving just the five least significant ones - which happens to match the remainder after dividing by 32) to find the specific bit it is interested in (1 << n makes a one-bit mask in position n, and the & operator filters out everything but that).

Unset uses ~, which inverts the mask - clearing the bit, leaving the rest the same. set uses the bitwise or operator, which sets a single bit.

So they are just convenience macros for working with individual bits in an array of integers.



来源:https://stackoverflow.com/questions/27592546/what-is-the-significance-of-these-defines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!