Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

delphi

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.

like image 722
Astaroth Avatar asked Oct 28 '25 18:10

Astaroth


1 Answers

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.

like image 129
David Heffernan Avatar answered Oct 31 '25 10:10

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!