i have a program in C#. and i want to print out what the program gets from serial.
cla开发者_如何学Css 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.
Your buffer
variable is a byte
array.
Console.WriteLine
does not have special handling for byte arrays, so it just prints the result of the ToString()
function.
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
.
Similar to what SLaks said, this would be the fix:
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. Loop through it and build a string first.
精彩评论