Home > Back-end >  Binary string and transform floating point Numbers
Binary string and transform floating point Numbers

Time:12-08

Consult, Delphi binary string, and how to implement the following floating-point mutual conversion formula:
0011 1101 1000 1111 0101 1100 0010 1001 & lt;=& gt; 0.07

This binary from the value of the type of PLC read DWord, I put all the bits out, can turn a Float, if direct DWord type that best,

Thank you very much!

CodePudding user response:

His answer, do not need to turn the binary string, directly turn Single DWord is ok, the hope can help others, spent several hours,

Function DWordToSingle (ASource: DWord) : Single;
Var
ByteArray containing: array [0.. 3] of byte;
The begin
ByteArray containing [3] :=HiByte (LoWord (ASource));
ByteArray containing [2] :=LoByte (LoWord (ASource));
ByteArray containing [1] :=HiByte (HiWord (ASource));
ByteArray containing [0] :=LoByte (HiWord (ASource));

Result:=PSingle (@ ByteArray containing) ^;
end;

The function SingleToDWord (ASource: Single) : DWord;
Var
TmpSingle: PSingle;
ByteArray containing: array [0.. 3] of byte;
WHighWord wLowWord: Word;
The begin
TmpSingle:=@ ASource;
Move (ASource ByteArray containing, SizeOf (ASource));

WHighWord:=MakeWord (ByteArray containing [0], ByteArray containing [1]).
WLowWord:=MakeWord (ByteArray containing [2], ByteArray containing [3]).

Result:=MakeLong (wLowWord wHighWord);
end;

The function DWordToBinary (const ASource: Dword) : string;
Var
I: Integer;
The begin
Result:=';

For I:=0 to 31 do
Result: the result=+ Format (' % x '[byte ((ASource SHR I) and 1)]);
end;

CodePudding user response:

 function BSWAP (d: LONGWORD) : LONGWORD; 
Asm
{$IFDEF CPUX64}
MOV EAX, ECX
{$ENDIF}
BSWAP EAX
end;

Function DWordToSingle (ASource: DWord) : Single;
The begin
ASource:=BSWAP (ASource);
Result:=PSingle (@ ASource) ^;
end;

The function SingleToDWord (ASource: Single) : DWord;
The begin
Result:=BSWAP (PLongWord (@ ASource) ^);
end;

CodePudding user response:

The answer is always one by one:
 
Rr=the packed record
In case the integer of
DW: 0: (DWORD);
1: (S: Single);
end;
Function DWordToSingle2 (ASource: DWord) : Single;
Var
R: rr.
The begin
R.d w:=asource;
Result:=r.S.
end;
ShowMessage (FloatToStr (DWordToSingle2 d8f5c29 ($3)));
  • Related