You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Delphi中将十六进制字符串转为TComPort可用的十六进制数据?

Converting Hex String to Byte Sequence for TComPort.WriteStr

Got it, let's solve this. Your goal is to take a space-separated hex string like "D5 D5" and convert it into the same byte sequence as the hardcoded #$D5#$D5 that works with WriteStr. Here's how to do it step by step:

Step-by-Step Explanation

  1. Split the Input String: Break down the space-separated hex pairs into individual segments (e.g., "D5 D5" becomes ["D5", "D5"]).
  2. Convert Each Hex Segment to a Byte: Turn each 2-character hex string into its corresponding byte value (e.g., "D5" becomes $D5 or 213 in decimal).
  3. Build a Byte-Encoded String: Construct a string where each character represents the byte value (this matches what #$XX does natively).
  4. Send the String via TComPort: Pass the built string to WriteStr to send the raw bytes.

Working Delphi Code

Here's a complete implementation using TStringList to handle splitting the input cleanly, plus error checking for invalid hex values:

procedure TForm1.Button3Click(Sender: TObject);
var
  HexSegments: TStringList;
  I: Integer;
  HexPart: string;
  ByteValue: Integer;
  OutputBytes: AnsiString;
begin
  HexSegments := TStringList.Create;
  try
    // Configure string list to split on spaces
    HexSegments.Delimiter := ' ';
    HexSegments.StrictDelimiter := True;
    HexSegments.DelimitedText := Trim(Edit1.Text);

    OutputBytes := '';

    for I := 0 to HexSegments.Count - 1 do
    begin
      HexPart := Trim(HexSegments[I]);

      // Validate hex segment length
      if Length(HexPart) <> 2 then
      begin
        ShowMessage(Format('Invalid hex segment: "%s" (must be 2 characters)', [HexPart]));
        Exit;
      end;

      try
        // Convert hex string to integer (byte value)
        ByteValue := StrToInt('$' + HexPart);
        // Append the byte as an AnsiChar to our output string
        OutputBytes := OutputBytes + AnsiChar(ByteValue);
      except
        on E: EConvertError do
        begin
          ShowMessage(Format('Failed to convert hex segment "%s": %s', [HexPart, E.Message]));
          Exit;
        end;
      end;
    end;

    // Send the raw byte sequence via TComPort
    ComPort1.WriteStr(OutputBytes);
  finally
    HexSegments.Free;
  end;
end;

Key Notes

  • Unicode Compatibility: Using AnsiString and AnsiChar ensures that each character is treated as a single byte, which is critical in newer Delphi versions (2009+) where string defaults to UTF-16 (2 bytes per character). This matches the behavior of the hardcoded #$D5 literals.
  • Error Handling: The code checks for invalid segment lengths and conversion errors, so you'll get clear feedback if the input isn't formatted correctly.
  • Input Flexibility: This works with any number of space-separated hex pairs (e.g., "01 02 03" will send three bytes: $01, $02, $03).

内容的提问来源于stack exchange,提问作者Martin Ocando Corleone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:29:15