C# 如何使字节值用作int
我试图使服务器能够接收客户端字节,并将其用作整数,我如何才能做到这一点?这是我试图修复的代码~唯一的错误是它无法将字节处理为int。。。请帮帮我C# 如何使字节值用作int,c#,user-interface,int,byte,C#,User Interface,Int,Byte,我试图使服务器能够接收客户端字节,并将其用作整数,我如何才能做到这一点?这是我试图修复的代码~唯一的错误是它无法将字节处理为int。。。请帮帮我 try { byte[] received = new byte[1024]; mStream.Read(received, 0, received.Length); updateUI("Received: " + Encodi
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;
}
或者,如果您使用与IDE类似的Visual Studio,则可以在执行过程中停止函数并检查值。您正在尝试将数组转换为int。这当然是不可能的。无法猜测预期的结果,received[0]只给出了接收到的数据的一个随机字节。不要忽略Read()的返回值。实际上,我将其设置为的客户端只向服务器发送了一个特定的数字,以根据数字执行案例。你能教我或给我一些想法,如何让服务器读取int或char而不是byte吗。在命令处,字节[]接收=新字节[1024];mStream.Read(received,0,received.Length);我尝试了你的方法,它不再给出任何错误,但是它停止了服务器。你能教我如何将字节转换成int并显示它吗,也许这会给我一个关于另一种方法的想法。
//Try converting the byte value and setting your int to it that way
int cir = Convert.ToInt32(recieved);
//Try writing the value in a console to see what you have
Console.WriteLine(received);
Console.Readline();