在Borland的Delphi转换浮动或负整数十六进制 [英] Converting float or negative integer to hexadecimal in Borland Delphi

查看:416
本文介绍了在Borland的Delphi转换浮动或负整数十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伊夫写入与使用串行连接一些硬件进行通信的程序。
它发出大量的十六进制值我的方式(传感器读数),并每隔一段时间发送一个负值。
恩。
我收到一个十六进制值:FFFFF5D6
我必须把它转换为:-2602

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 sends a negative value. ex. i receive a hexadecimal value : FFFFF5D6 and i have to convert it into : -2602

另一个问题,我有是,我不能转换成浮动十六进制和背部。

another problem i have is that i can't convert a float into hex and back.

是否有这样做的任何简单的方法?

Are there any simple ways of doing this?

推荐答案

您可以转换从十六进制使用足以覆盖使用的浮点值,然后用绝对<整数浮动/ code>关键字。所有这一切都真正做的是编码值作为一个整数的内存。要非常小心,要使用的是完全相同的大小型号(可以使用 SIZEOF 来找到一个值的内存大小)。如果你需要一个奇怪的尺寸,然后针对字节和循环数组绝对通过,并转换为/从每个字节(这将是两个字符十六进制)。

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;

这篇关于在Borland的Delphi转换浮动或负整数十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆