2

我试图让服务器能够接收客户端字节并将其用作整数,我该怎么做?这是我要修复的代码~唯一的错误是它无法将字节处理为 int ......请帮助我

try
             { 

                byte[] received = new byte[1024];
                mStream.Read(received, 0, received.Length);
                updateUI("Received: " + Encoding.ASCII.GetString(received));


                int Cir;
                Cir = received;

                switch (Cir)
                {
                    case 1 :
                        serialPort1.PortName = "COM5";
                        serialPort1.BaudRate = 9600;
                        serialPort1.DataBits = 8;
                        serialPort1.Parity = System.IO.Ports.Parity.None;
                        serialPort1.StopBits = System.IO.Ports.StopBits.One;
                        serialPort1.Open();
                        serialPort1.Write("a");
                        serialPort1.Close();
                        break;
                    case 2:
                        serialPort1.PortName = "COM5";
                        serialPort1.BaudRate = 9600;
                        serialPort1.DataBits = 8;
                        serialPort1.Parity = System.IO.Ports.Parity.None;
                        serialPort1.StopBits = System.IO.Ports.StopBits.One;
                        serialPort1.Open();
                        serialPort1.Write("a");
                        serialPort1.Close();
                        break;


                }
4

2 回答 2

0
//Try writing the value in a console to see what you have
Console.WriteLine(received);
Console.Readline(); 

或者,如果您使用 Visual Studios 之类的 IDE,您可以在执行过程中停止函数并检查值。

于 2013-06-16T18:47:25.353 回答
0
//Try converting the byte value and setting your int to it that way
int cir = Convert.ToInt32(recieved);

转换为 Int32

于 2013-06-16T17:07:39.390 回答