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

Delphi Tokyo 10.2中如何将TBits转换为整数/无符号整数

在Delphi Tokyo 10.2中实现TBits到整数/无符号整数的转换

针对你的需求,这里有几个实用的解决方案,从直观手动计算到高效内存操作都有,你可以根据场景选择:

方案一:手动遍历位计算(直观易懂)

这个方法适合需要清晰理解转换逻辑的场景,手动遍历每一位并累加对应的值:

function BitsToUInt32(const ABits: TBits): UInt32;
var
  I: Integer;
begin
  Result := 0;
  // 只处理前32位(UInt32的最大范围)
  for I := 0 to Min(ABits.Size - 1, 31) do
  begin
    if ABits.Bits[I] then
      Result := Result or (1 shl I);
  end;
end;

在你的代码里直接替换SomeBitsConvertToInteger调用即可:

var 
  ABits: TBits; 
  AComulative: UInt32; 
const 
  PosBitFromSensor1 = 0; 
  PosBitFromSensor2 = 1; 
begin 
  ABits := TBits.Create; 
  try 
    ABits.Size := 32; 
    ABits.Bits[PosBitFromSensor1] := GetValFromSensor(PosBitFromSensor1); 
    ABits.Bits[PosBitFromSensor2] := GetValFromSensor(PosBitFromSensor2); 
    // 使用自定义转换函数
    AComulative := BitsToUInt32(ABits); 
  finally 
    ABits.Free; 
  end; 
end;

方案二:利用TBits内置方法(高效简洁)

Delphi的TBits类提供了GetBits方法,可以直接将位数据复制到缓冲区,这种方法性能更高,适合处理大量位的场景:

function BitsToUInt32(const ABits: TBits): UInt32;
var
  LBuffer: UInt32;
begin
  FillChar(LBuffer, SizeOf(LBuffer), 0);
  // 只获取前32位数据
  if ABits.Size > 0 then
    ABits.GetBits(0, Min(ABits.Size, 32), @LBuffer);
  Result := LBuffer;
end;

方案三:跳过TBits直接计算(最优性能)

如果你的场景只需要处理少量几个传感器位(比如示例中的2位),完全可以跳过TBits的创建,直接通过位运算计算结果,减少内存开销:

var 
  AComulative: UInt32; 
const 
  PosBitFromSensor1 = 0; 
  PosBitFromSensor2 = 1; 
begin 
  // 直接将Boolean转成Ord(0或1)后做位运算
  AComulative := (Ord(GetValFromSensor(PosBitFromSensor1)) shl PosBitFromSensor1) or
                 (Ord(GetValFromSensor(PosBitFromSensor2)) shl PosBitFromSensor2);
end;

注意事项

  • 如果你的TBits实例包含超过32位的数据,UInt32只能存储低32位的值,高位会被截断。
  • 若需要转换为有符号整数(比如Int32),只需将函数返回类型改为Int32,逻辑完全一致。

内容的提问来源于stack exchange,提问作者Dicky Tamara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:13:25