Python TCP通信时如何将长度数值转为\x格式的十六进制字节
正确格式化十六进制长度字段的解决方案
核心错误原因:你当前是把长度数值转换成了十六进制格式的可读字符串(如"0x0B")进行拼接,实际需要直接写入对应数值的单字节二进制数据,而非字符串文本。
以下是不同常用开发语言的实现示例:
Python 实现
import binascii command = b"STATUS?UPDATE" cmd_length = len(command) # 按报文格式拼接二进制字节 send_command = b"\x00\x00\x00" + cmd_length.to_bytes(1, byteorder="big") + b"\x02" + command + b"\x0D\x0A" # 验证输出十六进制报文 print(binascii.hexlify(send_command, " ").decode()) # 输出结果:00 00 00 0b 02 53 54 41 54 55 53 3f 55 50 44 41 54 45 0d 0a
C 语言实现
#include <string.h> int main() { char command[] = "STATUS?UPDATE"; int cmd_len = strlen(command); char send_buf[128] = {0}; // 填充固定前缀 send_buf[0] = 0x00; send_buf[1] = 0x00; send_buf[2] = 0x00; // 直接写入长度字节,无需转十六进制字符串 send_buf[3] = cmd_len; send_buf[4] = 0x02; // 拷贝命令内容 memcpy(send_buf + 5, command, cmd_len); // 填充后缀回车换行 send_buf[5 + cmd_len] = 0x0D; send_buf[6 + cmd_len] = 0x0A; int total_send_len = 6 + cmd_len; return 0; }
Java 实现
import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; public class TcpPacket { public static void main(String[] args) { byte[] command = "STATUS?UPDATE".getBytes(StandardCharsets.US_ASCII); int cmdLength = command.length; ByteBuffer buffer = ByteBuffer.allocate(5 + cmdLength + 2); buffer.put(new byte[]{0x00, 0x00, 0x00}); // 直接写入长度字节 buffer.put((byte) cmdLength); buffer.put((byte) 0x02); buffer.put(command); buffer.put(new byte[]{0x0D, 0x0A}); byte[] sendCommand = buffer.array(); } }
注意事项
- 所有报文拼接操作都要基于二进制字节流/字节数组实现,不要使用普通字符串拼接,避免编码转换导致内容异常
- 如果后续命令长度可能超过255,需要提前确认长度字段占用的字节数和传输端序,修改对应写入逻辑即可,核心逻辑保持不变:直接写入数值的二进制形式,不要转成十六进制可读字符串。
内容的提问来源于stack exchange,提问作者Developer Gee
相关产品推荐
相关产品推荐

