位操作用于检查一个数字是否在特定范围 [英] Bit twiddling for checking whether a number is in particular range

查看:120
本文介绍了位操作用于检查一个数字是否在特定范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现一个有趣的位操作源\\ COMMON \\ UNI code \\ utf.h ICU库文件(国际组件的Uni code)。该位操作是主要用于检测一个数是否是在特定的范围内。

I found an interesting bit twiddling in "source\common\unicode\utf.h" file of ICU library (International Components for Unicode). The bit twiddling was intended for checking whether a number is in a particular range.

// Is a code point in a range of U+d800..U+dbff?
#define U_IS_LEAD(c) (((c)&0xfffffc00)==0xd800)

我想通了一个神奇的数字(0xfffffc00)来自:

I have figured out the magic number (0xfffffc00) come from:

MagicNumber = 0xffffffff - (HighBound - LowBound)

不过,我也发现,该公式并不适用于所有的任意范围。这里是否有人在公式工作什么情况知道吗?

However, I also found that the formula doesn't apply to every arbitrary range. Does somebody here know in what circumstance the formula works?

是否有另位摆弄用于检查数值是否在特定的范围内?

Is there another bit twiddling for checking whether a number is in particular range?

推荐答案

有关应用这些技巧,这些数字必须有一些共同的特点在他们的二进制重新presentation。

For these tricks to apply, the numbers must have some common features in their binary representation.

0xD800 == 0b1101_1000_0000_0000
0xDBFF == 0b1101_1011_1111_1111

这是什么测试确实是屏蔽掉低10位。这通常被写成

What this test really does is to mask out the lower ten bits. This is usually written as

onlyHighBits = x & ~0x03FF

此操作(而不是)后 onlyHighBits 的低10位,保证是零。这意味着,如果这个数字现在等于较低的范围内的间隔,它一直在某个地方之前的时间间隔。

After this operation ("and not") the lower ten bits of onlyHighBits are guaranteed to be zero. That means that if this number equals the lower range of the interval now, it has been somewhere in the interval before.

这个特技工作在所有情况下,在下和间隔的上限开始二进制相同数字,并且在某些点的下限仅具有零而较高极限具有唯一的。在您的例子,这是从右边的第十位。

This trick works in all cases where the lower and the higher limit of the interval start with the same digits in binary, and at some point the lower limit has only zeroes while the higher limit has only ones. In your example this is at the tenth position from the right.

这篇关于位操作用于检查一个数字是否在特定范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆