algorithm - 通过位运算符检查一个点是否在矩形内

标签 algorithm geometry bit-manipulation

几天前,我的老师告诉我可以仅使用位运算符来检查给定点是否在给定矩形内。是真的吗?如果可以,我该怎么做?

最佳答案

这可能无法回答您的问题,但您正在寻找的可能是这个。
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/

相关文章:

java - 判断一个三角形是不是钝角三角形

javascript - 在之前的 Canvas 上绘制一个旋转圆

language-agnostic - 如何计算球体上一点到线段的距离?

javascript - 如何缩短表示字符序列的位数

c - 将 9 位值的流作为字节写入 C 中的文件

c++ - 我可以在这里摆脱嵌套的 for 循环吗?

algorithm - 复制用户选择的文件时避免名称冲突的策略?

algorithm - 找出 64 位数量中设置了哪个位的有效方法

algorithm - 转换 UX `pan` 手势以设置没有上限的线性值的策略

c - 仅使用按位运算符以二进制形式执行算术运算