Recently, the Modbus protocol requires the conversion of floating point numbers. Originally, we wanted to follow the IEEE floating point structure. Google had a better solution, and pasted it for future use.Code(The code is just for illustration and you can organize it yourself ):
1. Convert the byte array to single and input parameters for processing.
Function bytestosingle (): single; <br/> var <br/> bsingle: array [0 .. 3] of byte; <br/> begin <br/> // 49e48e68 <br/> bsingle [3]: = $49; <br/> bsingle [2]: = $ E4; <br/> bsingle [1]: = $ 8e; <br/> bsingle [0]: = $68; <br/> result: = psingle (@ bsingle [0]) ^; <br/> end;
2. Convert single to byte array
Function singletobytes (): tbytes; <br/> var <br/> F: single; <br/> bsingle: array [0 .. 3] of byte; <br/> begin <br/> F := 1872333; <br/> move (F, bsingle, sizeof (f )); <br/> result: = bsingle; <br/> end;
Another version of singletobytes:
Function singletobytes (): tbytes; <br/> var <br/> N: single; <br/> bsingle: array [0 .. 3] of byte; <br/> begin <br/> N: = 1872333; <br/> bsingle [0]: = (pbyte (@ n) + 0) ^; // The first value <br/> bsingle [1]: = (pbyte (@ n) + 1) ^; // value of the second digit <br/> bsingle [2]: = (pbyte (@ n) + 2) ^; // value of the third digit <br/> bsingle [3]: = (pbyte (@ n) + 3) ^; // value of the fourth digit <br/> end;
Note that earlier versions of Delphi do not support pbyte operations, so pbyte (pchar (@ n) + 0) ^ can be used.