如何在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
- Split the Input String: Break down the space-separated hex pairs into individual segments (e.g., "D5 D5" becomes ["D5", "D5"]).
- Convert Each Hex Segment to a Byte: Turn each 2-character hex string into its corresponding byte value (e.g., "D5" becomes
$D5or 213 in decimal). - Build a Byte-Encoded String: Construct a string where each character represents the byte value (this matches what
#$XXdoes natively). - Send the String via TComPort: Pass the built string to
WriteStrto 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
AnsiStringandAnsiCharensures that each character is treated as a single byte, which is critical in newer Delphi versions (2009+) wherestringdefaults to UTF-16 (2 bytes per character). This matches the behavior of the hardcoded#$D5literals. - 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
相关产品推荐
相关产品推荐

