I'v to convert some sensorvalues from hex to double.
Hex '80c0' should be something like -19.2°C, 80bc = 18.8, 80bb = -18.7°C , 80b5= -19.9
Tried this:
Uses SdpoSerial, Strutils;
strValue:= Inttostr(Hex2Dec64('80c0'));
dblValue:= StrtoFloat(strValue);
Memo.Lines.add(FormatFloat('0.0', dblValue))
This seems to work for positive values, but not negative as shown above.
......
Tried this program #engkin (slightly modified).
Lazarus »Forum »Programming »General »[SOLVED] ¿How convert string hexadecimal in Double value?
Result is allways 0;
Can't see what's wrong so need some help.
{$mode ObjFPC}{$H+}
interface
uses
Classes;
function HexToDouble(const s: string): double;
implementation
//program Project1;
function HexToNibble(const hexvalue: char; out nibble: byte): boolean;inline;
begin
if hexvalue IN ['0'..'9'] then
nibble:=((ord(hexvalue)) and 15)
else
if char(byte(hexvalue) or $20) IN ['a'..'f'] then
nibble:=((ord(hexvalue)+9) and 15)
else
Exit(False);
Result := True;
end;
function HexToBin(HexValue, BinValue: PChar; BinBufSize: Integer): Integer;
var
i,j : integer;
h,l : byte;
begin
i:=binbufsize;
while (i>0) do
begin
if not HexToNibble(hexvalue^, h) then
break;
inc(hexvalue);
if not HexToNibble(hexvalue^, l) then
break;
j := l + (h shl 4);
inc(hexvalue);
binvalue^:=chr(j);
inc(binvalue);
dec(i);
end;
result:=binbufsize-i;
end;
function HexToDouble(const s: string): double;
type
TNum = record
case byte of
1:(n32: DWord);
2:(n64: QWord);
3:(fs : Single);
4:(fd : Double);
end;
var
i: TNum;
begin
i.n64:=0;
if s<>'' then HexToBin(@s[1],@i,sizeof(double));
if Length(s)<9 then
begin
i.n32:=BEtoN(i.n32);
// HexToDouble:=i.fs;
Result:=i.fs;
end
else
begin
i.n64:=BEtoN(i.n64);
// HexToDouble:=i.fd;
Result:=i.fd;
end;
end;