Bit twiddling for checking whether a number is in particular range

前端 未结 3 2163
甜味超标
甜味超标 2021-02-19 20:16

I found some interesting bit twiddling in \"source\\common\\unicode\\utf.h\" file of ICU library (International Components for Unicode). The bit twiddling is intend

3条回答
  •  别那么骄傲
    2021-02-19 20:37

    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
    

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

    onlyHighBits = x & ~0x03FF
    

    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.

提交回复
热议问题