几天前,我的老师告诉我可以仅使用位运算符来检查给定点是否在给定矩形内。是真的吗?如果可以,我该怎么做?
最佳答案
这可能无法回答您的问题,但您正在寻找的可能是这个。
These are the tricks由肖恩·埃隆·安德森 (Sean Eron Anderson) 编译,他甚至悬赏 10 美元奖励那些能找到一个错误的人。我在这里找到的最接近的东西是一个宏,它可以查找任何整数 X 是否有一个 word,即 between M and N
Determine if a word has a byte between m and n
When m < n, this technique tests if a word x contains an unsigned byte value, such that m < value < n. It uses 7 arithmetic/logical operations when n and m are constant. Note: Bytes that equal n can be reported by likelyhasbetween as false positives, so this should be checked by character if a certain result is needed.
Requirements: x>=0; 0<=m<=127; 0<=n<=128
#define likelyhasbetween(x,m,n) \ ((((x)-~0UL/255*(n))&~(x)&((x)&~0UL/255*127)+~0UL/255*(127-(m)))&~0UL/255*128)
This technique would be suitable for a fast pretest. A variation that takes one more operation (8 total for constant m and n) but provides the exact answer is:
#define hasbetween(x,m,n) \ ((~0UL/255*(127+(n))-((x)&~0UL/255*127)&~(x)&((x)&~0UL/255*127)+~0UL/255*(127-(m)))&~0UL/255*128)
关于algorithm - 通过位运算符检查一个点是否在矩形内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10052079/