c# – 从字节数组中读取行(不将字节数组转换为字符串)

前端之家收集整理的这篇文章主要介绍了c# – 从字节数组中读取行(不将字节数组转换为字符串)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个字节数组,我正在从NetworkStream中读取.前两个字节表示后面的数据包的长度,然后将数据包读入该长度的字节数组.我需要从NetworkStream / byte数组中读取的数据有几个字符串,即由新行字符终止的可变长度数据,以及一些固定宽度字段,如字节和长整数.所以,像这样:
// I would have delimited these for clarity but I didn't want
// to imply that the stream was delimited because it's not.
StringbyteStringStringbytebytebytelonglongbytelonglong

我知道(并且有一些说法)正在发生的数据包的格式,我需要做的是读取每个字符串值的“行”,但读取字节和长度的固定字节数.到目前为止,我提出的解决方案是使用while循环将字节读入临时字节数组,直到有换行符.然后,将字节转换为字符串.这对我来说似乎很尴尬,但我没有看到另一种显而易见的方式.我意识到我可以使用StreamReader.ReadLine(),但这将涉及另一个流,我已经有了一个NetworkStream.但如果这是更好的解决方案,我会试一试.

我考虑的另一个选项是让我的后端团队为那些String值的长度写一个或两个字节,这样我就可以读取长度,然后根据指定的长度读取字符串.

所以,正如你所看到的,我有一些选择如何解决这个问题,我希望你的意见是关于你认为最好的方法.这是我现在用于以字符串形式读取整个数据包的代码.下一步是打破数据包的各个字段,并根据数据包中的数据完成需要完成的实际编程工作,创建对象,更新UI等.

string line = null;  
while (stream.DataAvailable)
{  
    //Get the packet length;  
    UInt16 packetLength = 0;  
    header = new byte[2];  
    stream.Read(header,2);  
    // Need to reverse the header array for BitConverter class if architecture is little endian.  
    if (BitConverter.IsLittleEndian)
        Array.Reverse(header);  
    packetLength = BitConverter.ToUInt16(header,0);

    buffer = new byte[packetLength];
    stream.Read(buffer,BitConverter.ToUInt16(header,0));
    line = System.Text.ASCIIEncoding.ASCII.GetString(buffer);
    Console.WriteLine(line);
}

解决方法

就我个人而言

>将Int16放在开头
字符串,所以你知道多久
他们会成为,而且
>使用IO.BinaryReader类
读书,它会“读”,整理,
字符串,字符等变为变量,例如BinReader.ReadInt16()将读取两个字节,返回它们代表的int16,并在流中移动两个字节

希望这可以帮助.

附:使用ReadString方法时要小心,它假定字符串前面有自定义的7位整数,即它是由BinaryWriter类编写的.
以下是这篇CodeGuru的帖子

The BinaryWriter class has two methods
for writing strings: the overloaded
Write() method and the WriteString()
method. The former writes the string
as a stream of bytes according to the
encoding the class is using. The
WriteString() method also uses the
specified encoding,but it prefixes
the string’s stream of bytes with the
actual length of the string. Such
prefixed strings are read back in via
BinaryReader.ReadString().

The interesting thing about the length value it that as few bytes as possible are used to hold this size,it is stored as a type called a 7-bit encoded integer. If the length fits in 7 bits a single byte is used,if it is greater than this then the high bit on the first byte is set and a second byte is created by shifting the value by 7 bits. This is repeated with successive bytes until there are enough bytes to hold the value. This mechanism is used to make sure that the length does not become a significant portion of the size taken up by the serialized string. BinaryWriter and BinaryReader have methods to read and write 7-bit encoded integers,but they are protected and so you can use them only if you derive from these classes.

原文链接:https://www.f2er.com/csharp/99003.html

猜你在找的C#相关文章