使用TCP indy 9读取数据

时间:2011-02-22 14:45:57

标签: delphi delphi-7

在我的项目中,我需要开发服务器从GPRS / GPS Box接收帧并解码这些帧以提取相关数据,如纬度,经度等等

第一部分(TCP连接和接收数据)完成,我遇到的问题是解码数据,GPRS盒的固件发送数据不是字符串格式而是十六进制格式,所以我使用的方法(currentReaderBuffer)输出字符串格式的框架,让我用实例解释:

从GPRS BOX发送的数据是:0d 0a 1f 52 使用currentReaderBuffer接收的数据是:#$ d#$ a#1fR 问题是如何知道caracter#$ d是否对应于0d或者每个字符(#,$,d)是否对应于每个ascii代码

2 个答案:

答案 0 :(得分:1)

#$d表示它是十六进制(#)中的字符{$),其值为D(13),这意味着它是回车符。如果你总是得到1个字节的值(例如0D或'1F'),你可以非常确定它们是十六进制值并转换它们。

转换它们很容易。只需使用它们。

例如:

ShowMessage('You received hex 52, which is ' + #$52);

答案 1 :(得分:1)

事实上,你正在接收正确的数据,但你却以一种糟糕的方式解释它......并混合了一些概念:

十六进制只是数据的表示...计算机中的数据是二进制的,计算机不理解也不能用十六进制工作。

您选择将一个字节的数据表示为一个字符,但您可以将其视为一个字节,并从中执行该数据的十六进制表示。

例如:

var
  aByte: Byte;
begin
  //ReceivedStr is the string variable where you hold the received data right now
  aByte := ReceivedStr[1];  
  //Warning! this will work only in pre-2009 Delphi versions
  ShowMessage('Hexadecimal of first byte: ' + IntToHex(aByte);
end;

 function StringToHex(const S: string): string;  //weird!
 begin
  //Warning! this will work only in pre-2009 delphi versions
   Result := '';
   for I := 1 to Length(Result) do
     Result := Result + IntToHex(Byte(S[I])) + ' ';
 end;

 function ReceiveData();
 begin
   //whatever you do to get the data...

   ShowMessage('Received data in hex: ' + StringToHex(ReceivedStr));
 end;

这就是说,恕我直言最好从一开始就将数据视为二进制(整数,字节或任何其他合适的类型),避免使用字符串。当你想升级到现有的Delphi版本时,它会让你的生活变得更轻松,其中字符串是Unicode。

无论如何,您可能想要处理该数据,我认为您不打算直接向用户显示该数据。

如果要检查特定字节是否与十六进制值相对应,可以使用$表示法:

if aByte = $0d then
  ShowMessage('The hex value of the byte is 0d');