Delphi中是否有GCC的__builtin_popcountl等内置函数的等效实现?
Delphi中GCC内置位操作函数的等效实现
针对你提到的三个GCC内置位操作函数,Delphi有对应的内置函数(高版本)和通用兼容实现(全版本),具体如下:
1. __builtin_popcountl(x) 统计整数x中置位(1)的位数
- 高版本Delphi(XE2+):直接使用内置的
PopCnt函数,支持UInt32和UInt64类型,利用CPU硬件指令,效率极高:var x: UInt64; cnt: Integer; begin cnt := PopCnt(x); end; - 通用兼容实现:如果使用旧版Delphi,可通过经典位运算实现,兼容所有版本:
function PopCountL(const x: UInt64): Integer; var val: UInt64; begin val := x; Result := 0; while val <> 0 do begin Inc(Result); val := val and (val - 1); // 清除最低位的1 end; end;
2. __builtin_clz(x) 统计整数x中的前导零位数
- 高版本Delphi(XE3+):使用内置的
CountLeadingZeros函数,自动适配32/64位整数:
注意:GCC中var x: UInt32; zeroCnt: Integer; begin zeroCnt := CountLeadingZeros(x); end;__builtin_clz(0)行为未定义,而Delphi的CountLeadingZeros(0)会返回对应类型的总位数(32或64),若需匹配GCC的未定义行为,可自行添加x=0的特殊处理逻辑。 - 通用兼容实现:
// 32位整数版本 function CountLeadingZeros32(const x: UInt32): Integer; begin if x = 0 then Result := 32 // 按需调整,若要模拟未定义行为可抛出异常 else begin Result := 0; while (x shl Result) and $80000000 = 0 do Inc(Result); end; end; // 64位整数版本 function CountLeadingZeros64(const x: UInt64): Integer; begin if x = 0 then Result := 64 // 按需调整 else begin Result := 0; while (x shl Result) and $8000000000000000 = 0 do Inc(Result); end; end;
3. __builtin_ctz(x) 统计整数x中的尾随零位数
- 高版本Delphi(XE3+):使用内置的
CountTrailingZeros函数,适配32/64位整数:
注意:GCC中var x: UInt64; zeroCnt: Integer; begin zeroCnt := CountTrailingZeros(x); end;__builtin_ctz(0)行为未定义,Delphi的CountTrailingZeros(0)返回对应类型总位数,需特殊处理可自行修改。 - 通用兼容实现:
// 32位整数版本 function CountTrailingZeros32(const x: UInt32): Integer; begin if x = 0 then Result := 32 // 按需调整 else begin Result := 0; while (x shr Result) and 1 = 0 do Inc(Result); end; end; // 64位整数版本 function CountTrailingZeros64(const x: UInt64): Integer; begin if x = 0 then Result := 64 // 按需调整 else begin Result := 0; while (x shr Result) and 1 = 0 do Inc(Result); end; end;
内容的提问来源于stack exchange,提问作者zeus
相关产品推荐
相关产品推荐

