Bit twiddling for checking whether a number is in particular range

前端 未结 3 2229
甜味超标
甜味超标 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:27

    If you do not have 2^x boundaries type might use the following trick:

    if x >= 0 and x < N you can check both by:

      if Longword( x ) < Longword( N ) then ...
    

    This works due to the fact that negative numbers in signed numbers correspond to the largest numbers in unsigned datatypes.

    You could extend this (when range checking is DISABLED) to:

      if Longword( x - A ) < Longword ( ( B - A ) ) then ...
    

    Now you have both tests (range [ A, B >) in a SUB and a CMP plus a single Jcc, assuming (B - A ) is precalculated.

    I only use these kind of optimizations when really needed; eg they tend to make your code less readable and it only shaves off a few clock cycles per test.

    Note to C like language readers: Longword is Delphi's unsigned 32bit datatype.

提交回复
热议问题