You need to enable JavaScript to run this app. C#串口512字节数据数组解码重格式化时触发FormatException报错排查
优惠活动
大模型
产品
解决方案
定价
更多

C#串口512字节数据数组解码重格式化时触发FormatException报错排查

问题根因
  • 读取方式错误:串口传输的是原始二进制字节,使用ReadExisting()按字符串编码读取后,0xFC、0x00这类非打印字符会被转成无法被int.Parse识别的字符,直接触发格式异常。
  • 帧边界缺失:SerialPort的DataReceived事件不保证一次返回完整的512字节帧,存在分包情况。原代码直接对单次读取的片段解码,会遇到长度不足、解析错位的问题。
  • 字段逻辑错位:根据抓取的帧结构0x23(#) 0x42(B) 0xFC 0x01,长度字段为小端存储,实际值508对应(0x01 << 8) | 0xFC,原代码的字段读取索引、字节拼接顺序和实际传输规则不匹配。
  • 循环逻辑失效:原代码循环507次、每次读取4个字节拼接整数,累计需要2028字节输入,和512字节的总帧长完全不匹配。
优化方案
  • 改用原始字节读取方式处理二进制帧,避免字符编码转换带来的解析错误。
  • 增加帧缓存重组逻辑,将多次接收的零散字节拼接为完整帧,校验帧头和长度匹配后再执行解码。
  • 严格按照实际传输的字节偏移、小端序规则拼接数值,所有字段解析直接通过位运算实现,不依赖字符转换。
  • 对帧头、长度做有效性校验,避免无效数据进入解码流程。
修正后参考代码

接收逻辑改造

在类层级新增帧缓存字段:

private readonly byte[] frameBuffer = new byte[1024];
private int bufferPos = 0;
private const int FullFrameLength = 512;

private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
    var serialPort = (SerialPort)sender;
    byte[] readBuffer = new byte[serialPort.BytesToRead];
    int readCount = serialPort.Read(readBuffer, 0, readBuffer.Length);
    
    // 将读取到的字节追加到帧缓存
    if (bufferPos + readCount >= frameBuffer.Length)
    {
        bufferPos = 0;
        return;
    }
    Array.Copy(readBuffer, 0, frameBuffer, bufferPos, readCount);
    bufferPos += readCount;

    // 从缓存中匹配完整帧
    while (bufferPos >= FullFrameLength)
    {
        // 校验帧头是否为#(0x23)
        if (frameBuffer[0] != 0x23)
        {
            // 无有效帧头,移位丢弃1字节继续匹配
            bufferPos--;
            Array.Copy(frameBuffer, 1, frameBuffer, 0, bufferPos);
            continue;
        }
        // 取出完整帧送入解码流程
        byte[] fullFrame = new byte[FullFrameLength];
        Array.Copy(frameBuffer, 0, fullFrame, 0, FullFrameLength);
        dataDecoder(fullFrame);
        // 移除已解析的帧,剩余内容前移
        bufferPos -= FullFrameLength;
        Array.Copy(frameBuffer, FullFrameLength, frameBuffer, 0, bufferPos);
    }
}

解码逻辑改造

将解码方法的输入从字符串改为原始字节数组:

private void dataDecoder(byte[] frame)
{
    StringBuilder post = new StringBuilder("Decode, Len=");
    // 解析长度字段:索引2、3为小端序,对应值(0x01 <<8) | 0xFC = 508
    int len = (frame[3] << 8) | frame[2];
    post.Append(len);
    post.Append(" Channel: ");
    // 解析通道字段:索引4、5为小端序
    int chnl = (frame[5] << 8) | frame[4];
    post.Append(chnl);
    post.Append("DATA");

    // 解析数据区:从索引6开始,每4字节拼一个小端32位整数,到索引510停止(索引511为校验位)
    for (int offset = 6; offset < 511; offset += 4)
    {
        if (offset + 3 > 510) break;
        int rec = frame[offset] | (frame[offset+1] << 8) | (frame[offset+2] << 16) | (frame[offset+3] << 24);
        post.Append(rec);
        post.Append(',');
    }
    SetText(post.ToString());
}

说明:对于非#开头的普通文本类数据,可在帧匹配过程中将连续的非帧头字节按ASCII编码转成字符串,直接传入SetText展示,实现不同类型数据的分流处理。

内容的提问来源于stack exchange,提问作者sgt_johnny

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 01:45:01