有一个数据,如何截取我想要的长度 在我判断头帧后 我只想要后面的7位
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace Ck
{
public partial class Form1 : Form
{
string timeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
private List<byte> buffer = new List<byte>(1024);
byte[] receiveBuffer = new byte[10];
public Form1()
{
InitializeComponent();
}
private void Form1_Load_1(object sender, EventArgs e)
{
comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
button1.Text = "点击打开串口";
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.Open();
button1.Text = "点击关闭串口";
}
}
catch (Exception ex)
{
//捕获可能发生的异常并进行处理
//捕获到异常,创建一个新的对象,之前的不可以再用
serialPort1 = new System.IO.Ports.SerialPort();
//刷新COM口选项
comboBox1.Items.Clear();
comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
//响铃并显示异常给用户
System.Media.SystemSounds.Beep.Play();
button1.Text = "打开串口";
button1.BackColor = Color.ForestGreen;
MessageBox.Show(ex.Message);
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string abc;
// 检查是否允许跨线程调用控件,这里为了简化代码直接禁用了该功能
CheckForIllegalCrossThreadCalls = false;
// 读取所有可用字节数
int bytesToRead = serialPort1.BytesToRead;
//用于存储接收到的数据
byte[] receiveBuffer = new byte[bytesToRead];
//从串口读取数据
serialPort1.Read(receiveBuffer, 0, bytesToRead);
buffer.AddRange(receiveBuffer);
//将接收到的数据转换为字符串格式
string receivedString = BitConverter.ToString(receiveBuffer).Replace("-", "");
//将字符串追加至文本框中
if (buffer[0] ==0x68)
{
StreamWriter sw = new StreamWriter(@"C:\Users\guoxiaoru\Desktop\ACVB.txt", true);
sw.WriteLine(receivedString, "\n");
sw.Close();
}
}
}
}