What is Delphi's C equivalent __builtin_clz ()?
Quoting 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 Delphi equivalent to C __builtin_clz ()? If it doesn't, how do you effectively implement it in Delphi?
Actually, I want to use it to calculate the base-2 logarithm of an integer.
source to share
If you only want 32-bit code, it will look 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, this 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 is likely that the asm guru can be truncated a bit, but BSR
(reverse bit scanning) is a key instruction.
For mobile compilers, I don't know how to do this efficiently.
source to share