忙了一下午,终于做出来了 :)
function TForm1.DoubleToHex(iNum: Double): string;
var
i , nbit ,tmpInt :integer;
rank , mantissa , sDec:string;
sign : boolean;
tmpDec :double;
begin
nbit := 0;
//符号位
if iNum >0 then
sign := true
else begin
sign := false;
iNum := abs(iNum);
end;
tmpInt := Trunc(iNum);
//整数+小数
if tmpInt >0 then
begin
//取阶码
while tmpInt > 0 do
begin
tmpInt := tmpInt shr 1;
nbit := nbit + 1;
end;
//取尾数
for i := 1 to 16 - nbit do
iNum := iNum * 2;
mantissa := InttoHex(Trunc(iNum),4);
end else
//纯小数
begin
sDec :='';
tmpDec := iNum;
while tmpDec >0 do
begin
tmpDec :=tmpDec * 2;
if tmpDec >=1 then
begin
sDec :=sDec + '1';
tmpDec := tmpDec - 1;
end else
sDec := sDec +'0';
end;
//取阶码
for i := 1 to length(sDec) do
begin
if copy(sDec, i,1)='1' then
begin
sDec := copy(sDec , i ,length(sDec)- i + 1);
break;
end;
nbit := nbit + 1;
end;
//取尾数
if length(sDec)<16 then
begin
for i := 1 to 16 - length(sDec) do
sDec := sDec +'0';
end
else begin
sDec := copy(sDec , 1 , 16);
end;
nbit := -1 * nbit;
mantissa := IntToHex(BinToInt(sDec),4);
end;
if sign then
//40H + n
rank := IntToHex(64 + nbit , 2)
else
//C0H + n
rank := IntToHex(192 + nbit , 2);
Result := Copy(mantissa , 3 ,2) + copy(mantissa , 1 ,2) + rank;
end;