dakna
dakna

Reputation: 11

Reading data with TCP indy 9

in my project I need to developp server receiving frames from GPRS/GPS Box and decode theses frames to extract relevant data as latitude , longitude and more

the first part (TCP connection and receiving data) is done , the problem I had is with decode data, the firmware of GPRS box send data not in string format but in hex format , so the methode I used (currentReaderBuffer) ouput the frame with string format , let me explain with real example :

The data sent from GPRS BOX is : 0d 0a 1f 52 data received using currentReaderBuffer is : #$d#$a#1fR the problem is how can I know if the caracter #$d correspond to 0d or each of the caracters (#,$,d) correspond to each ascii code

Upvotes: 0

Views: 958

Answers (2)

jachguate
jachguate

Reputation: 17203

You're, in fact, receiving the correct data, but you're interpreting it in a bad way... and mixing some concepts:

Hex is just a representation of data... data in a computer is binary and computers does not understand nor work in hex.

You are choosing to represent a byte of data as a character, but you can treat it as a byte and from that perform a hex representation of that data.

For example:

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;

or

 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;

This said, IMHO is better to treat the data as binary from the start (Integers, bytes or any other suitable type), avoiding using strings. It will make your life easier now and then, when you want to upgrade to modern Delphi versions, where strings are Unicode.

Anyway, you may want to process that data, I don't think your intention is to show it directly to the user.

If you want to check if a particular byte against a hex value, you can use the $ notation:

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

Upvotes: 1

Ken White
Ken White

Reputation: 125749

#$d means it's a Char (#) in hex ($) with the value D (13), which means it's a carriage return. If you're always getting 1 byte values (for instance 0D or `1F'), you can be pretty sure they're hex values and convert them.

Converting them is easy. Just use them.

For instance:

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

Upvotes: 1

Related Questions