Converting float or negative integer to hexadecimal in Borland Delphi

前端 未结 4 2097
南旧
南旧 2021-01-23 22:51

Ive written a program that communicate with some hardware using a serial connection. It sends a lot of hexadecimal values my way (sensor readings) and every once in a while it s

4条回答
  •  旧巷少年郎
    2021-01-23 23:11

    You can "convert" from hex to float by using an integer large enough to cover the float value used, then using the ABSOLUTE keyword. All that is really doing is encoding the memory of the value as an integer. Be very careful to use types which are exactly the same size (you can use SIZEOF to find the memory size of a value). If you need an odd size, then absolute against an array of byte and loop through and convert to/from each byte (which would be two characters hex).

    the ABSOLUTE keyword forces two variables to START at the same memory address, any value written from one is immediately available in the other.

    var
      fDecimal : Double; // size = 8 bytes
      fInteger : Int64 absolute fDecimal;  // size = 8 bytes
    begin
      fDecimal := 3.14;
      ShowMessage(format('%x=%f',[fInteger,fDecimal]));
      fInteger := StrToInt64('$1234123412341234');
      ShowMessage(FloatToStr(fDecimal)+'='+Format('%x',[fInteger]));
    end;
    

    here is the routine for floats with odd sizes:

    var
      fDecimal : extended;
      fInteger : array[1..10] of byte absolute fDecimal;
      sHex     : string;
      iX       : integer;
    begin
      ShowMessage(IntToStr(SizeOf(fDecimal))+':'+IntToStr(SizeOf(fInteger)));
      fDecimal := 3.14;
      sHex := '';
      for iX := 1 to 10 do
        sHex := sHex + IntToHex(fInteger[iX],2);
      ShowMessage(sHex);
      // clear the value
      fDecimal := 0.0;
      // Reload the value
      for iX := 1 to (Length(sHex) DIV 2) do
        fInteger[iX] := StrToInt('$'+Copy(sHex,(Ix*2)-1,2));
      ShowMessage(FloatToStr(fDecimal));
    end;
    

提交回复
热议问题