Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Bytes to Single

Tags:

delphi

Is this the way to convert a 4 byte array into a Single in Delphi?

type
  RFloatToBytes = packed record
    case IsFloat: Boolean of
      True: (SingleVal: Single);
      False: (ByteVals: array[0..3] of Byte);
  end;
...

function XP_BytesToSingle(const B: array of Byte): Single;
Var
  Locale: RFloatToBytes;
begin
  Locale.ByteVals[0] := B[0];
  Locale.ByteVals[1] := B[1];
  Locale.ByteVals[2] := B[2];
  Locale.ByteVals[3] := B[3];
  Result := Locale.SingleVal;
end;

I tried to find a function like function BytesTo... in the unit IdGlobal but no conversion is provided for float, Extended, Single.

like image 675
Giovanni Brambilla Avatar asked Sep 15 '26 23:09

Giovanni Brambilla


1 Answers

Your code should work as-is, but you could also use one of these:

FUNCTION XP_BytesToSingle(CONST B : ARRAY OF BYTE) : Single;
  BEGIN
    MOVE(B[LOW(B)],Result,SizeOf(Single))
  END;

or

FUNCTION XP_BytesToSingle(CONST B : ARRAY OF BYTE) : Single;
  VAR
    S : Single ABSOLUTE B;

  BEGIN
    Result:=S
  END;

You don't need the "IsFloat" field. It just takes up space in your record:

type
  RFloatToBytes = packed record
        case Boolean of
          True: (SingleVal: Single);
          False: (ByteVals: array[0..3] of Byte);
        end;
like image 80
HeartWare Avatar answered Sep 17 '26 23:09

HeartWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!