我可以使用 SerialPort.Write 发送字节数组吗
Can I use SerialPort.Write to send byte array
SerialPort
Write
的文档说
By default, SerialPort uses ASCIIEncoding to encode the characters.
ASCIIEncoding encodes all characters greater than 127 as (char)63 or
'?'. To support additional characters in that range, set Encoding to
UTF8Encoding, UTF32Encoding, or UnicodeEncoding.
另见 here。这是否意味着我无法使用 write
发送字节数组?
By default, SerialPort uses ASCIIEncoding to encode the characters
您将 read/write string
或 char
的方法与 read/write bytes
.[=27= 的方法混淆了]
例如,当您调用它时:
port.Write("абв")
你会得到“???” (0x3F
0x3F
0x3F
) 默认在端口缓冲区中。另一方面,这个调用:
// this is equivalent of sending "абв" in Windows-1251 encoding
port.Write(new byte[] { 0xE0, 0xE1, 0xE2 }, 0, 3)
将直接写入序列 0xE0
0xE1
0xE2
,而不将字节替换为 0x3F
值。
UPD.
让我们看一下源代码:
public void Write(string text)
{
// preconditions checks are omitted
byte[] bytes = this.encoding.GetBytes(text);
this.internalSerialStream.Write(bytes, 0, bytes.Length, this.writeTimeout);
}
public void Write(byte[] buffer, int offset, int count)
{
// preconditions checks are omitted
this.internalSerialStream.Write(buffer, offset, count, this.writeTimeout);
}
你看出区别了吗?
接受 string
的方法将字符串转换为 byte
数组,使用当前的端口编码。接受 byte
数组的方法,将其直接写入流,该流是原生 API.
的包装器
是的,文档会骗你。
这个
port.Encoding = System.Text.Encoding.UTF8;
string testStr = "TEST";
port.Write(testStr);
还有这个
byte[] buf = System.Text.Encoding.UTF8.GetBytes(testStr);
port.Write(buf, 0, buf.Length);
将导致传输相同的字节。在后一个中,串口的编码可以是任何东西。
串口编码仅对读取或写入字符串的方法有影响。
SerialPort
Write
的文档说
By default, SerialPort uses ASCIIEncoding to encode the characters. ASCIIEncoding encodes all characters greater than 127 as (char)63 or '?'. To support additional characters in that range, set Encoding to UTF8Encoding, UTF32Encoding, or UnicodeEncoding.
另见 here。这是否意味着我无法使用 write
发送字节数组?
By default, SerialPort uses ASCIIEncoding to encode the characters
您将 read/write string
或 char
的方法与 read/write bytes
.[=27= 的方法混淆了]
例如,当您调用它时:
port.Write("абв")
你会得到“???” (0x3F
0x3F
0x3F
) 默认在端口缓冲区中。另一方面,这个调用:
// this is equivalent of sending "абв" in Windows-1251 encoding
port.Write(new byte[] { 0xE0, 0xE1, 0xE2 }, 0, 3)
将直接写入序列 0xE0
0xE1
0xE2
,而不将字节替换为 0x3F
值。
UPD.
让我们看一下源代码:
public void Write(string text)
{
// preconditions checks are omitted
byte[] bytes = this.encoding.GetBytes(text);
this.internalSerialStream.Write(bytes, 0, bytes.Length, this.writeTimeout);
}
public void Write(byte[] buffer, int offset, int count)
{
// preconditions checks are omitted
this.internalSerialStream.Write(buffer, offset, count, this.writeTimeout);
}
你看出区别了吗?
接受 string
的方法将字符串转换为 byte
数组,使用当前的端口编码。接受 byte
数组的方法,将其直接写入流,该流是原生 API.
是的,文档会骗你。
这个
port.Encoding = System.Text.Encoding.UTF8;
string testStr = "TEST";
port.Write(testStr);
还有这个
byte[] buf = System.Text.Encoding.UTF8.GetBytes(testStr);
port.Write(buf, 0, buf.Length);
将导致传输相同的字节。在后一个中,串口的编码可以是任何东西。
串口编码仅对读取或写入字符串的方法有影响。