将serialport.readline()非ascii字符串转换为字节数组 [英] convert serialport.readline() non-ascii string into a byte array
问题描述
我想使用 serialport.readline(),因为它是一个阻塞调用,我得到的数据最后有0x0D 0x0A(CR LF)。但是,我想要的是一个十六进制字符串而不是一个Ascii表示。
例如,我正在通信的设备是发送像{0xff,0xff,0x45 ,0X0D,的0x0A}。我想简单地打印出我的程序,就像这样:0xff,0xff,0x45。 Readline()可以修剪LF和CR。
尽管通过指定如何使用 serialport.read(buff [] ...)我想读的很多字节但是它没有很好的工作,因为如果我读得太快,那么数组的一半将为0x00,如果我读取的速度太慢,那么COM端口会出现溢出。我不想丢失任何字节。
我尝试将从 serialport.readline()获得的内容转换为字节数组,但是我得到的十六进制字符串通常变为 0x3F的即可。代码如下:
var line = string.Join(,,mySerialPort.ReadLine() >((Byte)c).ToString(X))ToArray());
我改变了编码几次(ASCII,UTF8,UNICODE),但仍然没有去。 p>
有没有办法将从 readline()获得的非Ascii 字符串转换为字节数组? / p>
听起来你不应该把它作为文本读取。 >
你从根本上处理二进制数据,所以使用 读取
,它采用字节数组而不是 char 数组。 (或者重复调用 ReadByte
)
任何时候您尝试将任意二进制数据视为文本, / p>
听起来你已经尝试过了,但是做得很糟糕:
但它没有很好的工作,因为如果我读得太快,数组的一半将是0x00
这表示您忽略 Read
的返回值,该值表示实际读取了多少个字节。你应该有这样的东西:
int bytesRead = port.Read(buffer,0,buffer.Length);
//现在使用从0(包括)到
// bytesRead(exclusive)的缓冲区的部分。
I want to use serialport.readline() because it's a blocking call and the data I'm getting has 0x0D 0x0A (CR LF) at the end. However, what I want is an Hex String instead of an Ascii representation.
For example, the device I am communication with is sending byte arrays like {0xff,0xff,0x45,0x0D,0x0A}. I want to simply print out in my program just like this: 0xff, 0xff,0x45. Readline() kindly trims out LF and CR.
I though about using serialport.read(buff[]...) by specifying how many bytes I want to read. But it didn't work very well because if I am reading too fast half of the array will be 0x00 and if I am reading too slow, there will be an overflow for the com port. I don't want to lose any bytes.
I tried to convert what I got from serialport.readline() to a byte array but the hex string I got usually turns into 0x3f. Code is like this:
var line = string.Join(",", mySerialPort.ReadLine().Select(c => ((Byte)c).ToString("X")).ToArray());
I changed the encoding a few times (ASCII, UTF8,UNICODE) but still no go.
Is there any way to convert the non-Ascii String I got from readline() into a byte array?
It sounds like you shouldn't be reading it as text data at all.
You're fundamentally dealing with binary data, so use the overload of Read
which takes a byte array rather than a char array. (Or call ReadByte
repeatedly.)
Any time you try to treat arbitrary binary data as if it's text, you're going to have a bad experience.
It sounds like you've already tried this, but done it badly:
But it didn't work very well because if I am reading too fast half of the array will be 0x00
That suggests you're ignoring the return value of Read
, which says how many bytes have actually been read. You should have something like:
int bytesRead = port.Read(buffer, 0, buffer.Length);
// Now use the portion of buffer which is from 0 (inclusive) to
// bytesRead (exclusive).
这篇关于将serialport.readline()非ascii字符串转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!