Martin Ocando Corleone
Martin Ocando Corleone

Reputation: 104

How to convert a Hexadecimal string to a Hexadecimal data in Delphi?

I am using the TComPort library, to send a request to the device I need to send the command in Hexadecimal data like the example below

procedure TForm1.Button3Click(Sender: TObject);
begin
  ComPort1.WriteStr(#$D5#$D5);
end;  

But that is a hardcoded example.

How can I convert S into a valid value for ComPort1.WriteStr

procedure TForm1.Button3Click(Sender: TObject);
var
  S:String;
begin
  Edit1.Text:='D5 D5';
  ComPort1.WriteStr(Edit1.Text);
end;  

Upvotes: 0

Views: 2379

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598309

You don't send actual hex strings over the port. That is just a way to encode binary data in source code at compile-time. #$D5#$D5 is encoding 2 string characters with numeric values of 213 (depending on {$HIGHCHARUNICODE}, which is OFF by default).

TComPort.WriteStr() expects actual bytes to send, not hex strings. If you want the user to enter hex strings that you then send as binary data, look at Delphi's HexToBin() functions for that conversion.

That being said, note that string in Delphi 2009+ is 16-bit Unicode, not 8-bit ANSI. You should use TComPort.Write() to send binary data instead of TComPort.WriteStr(), eg:

procedure TForm1.Button3Click(Sender: TObject);
var
  buf: array[0..1] of Byte;
begin
  buf[0] := $D5;
  buf[1] := $D5;
  ComPort1.Write(buf, 2);
end;  

However, TComPort.WriteStr() will accept a 16-bit Unicode string and transmit it as an 8-bit binary string by simply stripping off the upper 8 bits of each Char. So, if you send a string containing two Char($D5) values in it, it will be sent as 2 bytes $D5 $D5.

Upvotes: 2

Related Questions