如何将rfid的标签号拆分为整数?

时间:2019-03-23 13:34:47

标签: c# arduino rfid

我是通过读取卡来获取信息的,但是我怎样才能将标签号设为int?

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)
            {
                serialPort1.Open();
                serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            }

            MessageBox.Show("Success");
        }
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();
            textRFID.Text += indata;
        }

rfid-ss

这是我需要解析的字符串:

"RFID tag detected Tag Type:\tMifare One (S50) The tag's number is:\t235717311 Read Checksum:\t238 Calculated Checksum:\t238"

感谢@haldo,我可以收到标签号,但是它给出“对象引用未设置为对象实例”的错误,我尝试了catch,当我按OK进行错误操作时,它就输出了所需的输出。我们如何消除此错误?

这是我的编辑代码:

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            string contains = "The tag's number is:";
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();
            int tagNumber = 0;
            try
            {
                indata.Split(Environment.NewLine.ToCharArray())      // split on newline chars
                      .FirstOrDefault(s => s.Contains(contains)) // get first string matching pattern above 
                      .Split(':')                                    // split on ':'
                      .FirstOrDefault(x => int.TryParse(x, out tagNumber));  // return first successful try parse
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            textRFID.Text = tagNumber.ToString();            
        }

2 个答案:

答案 0 :(得分:1)

为什么不使用SubstringString.split('')之类的字符串操纵器。您将获得Tag number,然后使用Convert.ToInt(your tag number here)转换为INT。默认情况下为string。您需要将其转换为Integer

答案 1 :(得分:1)

您可以使用正则表达式查找模式并捕获“标记的编号为:”之后的一组数字,然后将捕获的字符串解析为int。像这样:

string pattern = "The tag's number is:(\\d+)";
string indata = "blah blah \nasdfasdfasdf\nThe tag's number is:123389882\nasdfsadf\nfgjdjgjgd";
var matches = Regex.Match(indata, pattern);
int? tagNumber = null;

if (matches.Success)
{
    var grp = matches.Groups[1];
    string num = grp.Value;
    tagNumber = int.Parse(num);
}

// tagNumber is 123389882