You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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位整数:
    var
      x: UInt32;
      zeroCnt: Integer;
    begin
      zeroCnt := CountLeadingZeros(x);
    end;
    
    注意:GCC中__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位整数:
    var
      x: UInt64;
      zeroCnt: Integer;
    begin
      zeroCnt := CountTrailingZeros(x);
    end;
    
    注意:GCC中__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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 21:53:15