c# 字节数组网路传输转义
/// <summary> /// 获取转义数据 /// 转义规则:0x9e<——>0x9d后紧跟一个0x02;0x9d<——>0x9d后紧跟一个0x01。 /// </summary> /// <param name="buffer">原始数据</param> /// <returns>转义数据</returns> private byte[] getTransferredMeaning(byte[] buffer) { try { List<byte> dataList = buffer.ToList(); for (int i = 1; i < dataList.Count-1; i++) { if (dataList[i] == 0x9e) { dataList[i] = 0x9d; dataList.Insert(i + 1, 0x02); } else if (dataList[i] == 0x9d) { dataList.Insert(i + 1, 0x01); } } return dataList.ToArray(); } catch { return buffer; } } /// <summary> /// 反转义 /// 转义规则:0x9e<——>0x9d后紧跟一个0x02;0x9d<——>0x9d后紧跟一个0x01。 /// </summary> /// <param name="buffer">原始数据</param> /// <returns>反转义数据</returns> private byte[] getOppositeMeaning(byte[] buffer) { try { List<byte> dataList = buffer.ToList(); for (int i = 1; i < dataList.Count - 1; i++) { if (dataList[i] == 0x9d && dataList[i + 1] == 0x02) { dataList[i] = 0x9e; dataList.RemoveAt(i + 1); } else if (dataList[i] == 0x9d && dataList[i + 1] == 0x01) { dataList.RemoveAt(i + 1); } } return dataList.ToArray(); } catch { return buffer; } }