[英]problem with C# printing from a serial buffer
i have a program in C#. 我有一个C#程序。 and i want to print out what the program gets from serial.
而且我想打印出程序从串行获取的内容。
class Serial
{
public static void Main()
{
byte[] buffer = new byte[256];
using (SerialPort sp = new SerialPort("COM2", 6200))
{
sp.Open();
//read directly
sp.Read(buffer, 0, (int)buffer.Length);
//read using a Stream
sp.BaseStream.Read(buffer, 0, (int)buffer.Length);
Console.WriteLine(buffer);
}
}
}
The program writes out System.byte[] and then quits. 程序将写出System.byte [],然后退出。
Your buffer
variable is a byte
array. 您的
buffer
变量是一个byte
数组。
Console.WriteLine
does not have special handling for byte arrays, so it just prints the result of the ToString()
function. Console.WriteLine
对字节数组没有特殊处理,因此它仅打印ToString()
函数的结果。
If you want to print meaningful content, you will need to create a string from the byte array that contains your content. 如果要打印有意义的内容,则需要从包含您的内容的字节数组中创建一个字符串。
You probably want to call Convert.ToBase64String
, Encoding.ASCII.GetString
, or BitConverter.ToString
. 您可能要调用
Convert.ToBase64String
, Encoding.ASCII.GetString
或BitConverter.ToString
。
Similar to what SLaks said, this would be the fix: 与SLaks所说的类似,此方法可以解决:
string bufferText = System.Text.Encoding.Default.GetString(buffer);
Console.WriteLine(bufferText);
Because byte[].ToString()
does not nicely print each element of the array, it prints the name of the type. 因为
byte[].ToString()
不能很好地打印数组的每个元素,所以它会打印类型的名称。 Loop through it and build a string first. 循环遍历并首先构建一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.