简体   繁体   English

Delphi将一组位转换为TBits到Integer或unsigned int

[英]Delphi Convert Set Of Bits as TBits to Integer or unsigned int

Ihave value from nor or xor gate with represented as TBits and i want to convert it to generic variable like integer or unsigned integer my current working ide Tokyo 10.2 我从nor或xor门得到的值用TBits表示,我想将其转换为通用变量,例如整数或无符号整数,我目前的工作环境是东京10.2

var
  ABits: TBits;
  AComulative: UInt32;

const
  PosBitFromSensor1 = 0;
  PosBitFromSensor2 = 1;

begin
  ABits := TBits.Create;
  try
    ABits.Size := 32;
    {GetValFromSensor return Boolean type}
    ABits.Bits[PostBitFromSensor1] := GetValFromSensor(PosBitFromSensor1); 
    ABits.Bits[PostBitFromSensor2] := GetValFromSensor(PosBitFromSensor2);
    AComulative := SomeBitsConvertToInteger(ABits); {some function like this}
  finally
    ABits.Free;
  end;
end;

or any simple solution. 或任何简单的解决方案。

maybe something like this : 也许是这样的:

type

  {$IF CompilerVersion > 32} // tokyo
    {$MESSAGE Fatal 'Check if TBits still has the exact same fields and adjust the IFDEF'}
  {$ENDIF}
  TPrivateAccessBits = class
  public
    FSize: Integer;
    FBits: Pointer;
  end;

Move(@TPrivateAccessBits(ABits).FBits, AComulative, sizeOf(AComulative));

this solution provided by @Victoria and @LURD it maybe usefull for the other that have same solving problem. @Victoria和@LURD提供的解决方案可能对其他具有相同解决问题的解决方案很有用。 sorry about my English. 对不起我的英语。

type
  TBitsHelper = class helper for TBits
  public
    function ToUInt32: UInt32;
  end;

{ TBitsHelper }

function TBitsHelper.ToUInt32: UInt32;
type
  PUInt32 = ^UInt32;
begin
  if Size > SizeOf(Result) * 8 then
    raise EOverflow.Create('Size overflow!');
  with Self do
    Result := PUInt32(FBits)^;
end;

It won't be very fast but you can do regular bit manipulation, set each bit that corresponds to a "true" in the boolean array . 速度不会很快,但是您可以进行常规的位操作,在布尔数组中设置与“ true”相对应的每个位。 For example: 例如:

function SomeBitsConvertToInteger(ABits: TBits): UInt32;
var
  i: Integer;
begin
  if ABits.Size <> SizeOf(Result) * 8 then
    raise EBitsError.Create('Invalid bits size');
  Result := 0;
  for i := 0 to Pred(SizeOf(Result) * 8) do
    Result := Result or UInt32((Ord(ABits[i]) shl i));
end;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM