开发者

problem with C# printing from a serial buffer

开发者 https://www.devze.com 2023-01-20 01:00 出处:网络
i have a program in C#. and i want to print out what the program gets from serial. cla开发者_如何学Css Serial

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消