Astaroth
Astaroth

Reputation: 2291

What is the Delphi equivalent to the C __builtin_clz()?

Quoted from https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html,

— Built-in Function: int __builtin_clz (unsigned int x) Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.

What is the Delphi equivalent to the C __builtin_clz() ? If there isn't, how to implement it efficiently in Delphi?

Actually, I want to use it to calculate the base-2 logarithm of an integer.

Upvotes: 4

Views: 357

Answers (1)

David Heffernan
David Heffernan

Reputation: 613013

If you only care about 32 bit code then it goes like this:

function __builtin_clz(x: Cardinal): Cardinal;
asm
  BSR     EAX,EAX
  NEG     EAX
  ADD     EAX,32
end;

Or if you want to support 64 bit code as well then it would be:

function __builtin_clz(x: Cardinal): Cardinal;
{$IF Defined(CPUX64)}
asm
  BSR     ECX,ECX
  NEG     ECX
  ADD     ECX,31
  MOV     EAX,ECX
{$ENDIF}
{$IF Defined(CPUX86)}
asm
  BSR     EAX,EAX
  NEG     EAX
  ADD     EAX,31
{$ENDIF}
end;

It's likely that an asm guru could trim this down a little, but BSR (bit scan reverse) is the key instruction.

For the mobile compilers, I don't know how to do this efficiently.

Upvotes: 4

Related Questions