Search code examples
delphidelphi-10.2-tokyo

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

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.


Solution

  • 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 . 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;