[英]Parsing byte array that contains different types of data
我有一個1250字節長的固定長度字節數組。 它可能包含以下類型的數據:
對象A由5個字節組成。 第一個字節包含字母“A”,接下來的四個字節存儲1到100000的整數。
對象B由2個字節組成。 第一個字節包含字母“B”,下一個字節包含1到100的整數。
對象C由50個字節組成。 所有50個字節用於存儲ASCII編碼的字符串,該字符串僅包含數字和以下字符: - +(和)
我不知道每個對象類型有多少在字節數組中,但我知道它們被組合在一起(對象B,對象B,對象A,對象A,對象A,對象C等)。 大多數情況下,當我解析一個字節數組時,該數組包含一種類型的數據(例如,所有項目都是對象A),所以我確切知道每個項目包含多少字節,我只是循環處理字節的數組。 在這種情況下,我有三種不同類型的數據,它們的長度都不同。 我以為我需要做這樣的事情:
int offset = 0;
while (offset <= 1250)
{
string objectHeader = Encoding.ASCII.GetString(byteArray, offset, 1);
if (objectHeader.Equals("A"))
{
// read 4 more bytes and then convert into int value (1 - 100000)
index += 5;
}
else if (objectHeader.Equals("B"))
{
// read 1 more byte and then convert into int value (1 - 100)
index += 2;
}
else
{
// read 49 more bytes and then convert into a string
index += 50;
}
}
有沒有更好的方法呢?
好吧,似乎與偏移和索引有點混淆,也許你應該使用for循環:
for(int index = 0; index < 1250; index++)
{
switch(byteArray[index])
{
case (byte)'A':
index++;
int value = BitConverter.ToInt32(byteArray, index);
index += 4;
break;
case (byte)'B':
index++;
// Read the next byte as integer.
int value = (int)byteArray[index];
index++;
break;
case (byte)'C': // string.
index++;
// Read the next 49 bytes as an string.
StringBuilder value = new StringBuilder(49);
for(int i = index; i < index + 49; index++)
{
if (byteArray[i] == 0) break;
value.Append(Converter.ToChar(byteArray[i]));
}
index+= 49;
break;
case 0: // Finished.
index = 1250;
break;
default:
throw new InvalidArgumentException("Invalid byte array format");
}
}
你如何看待沒有更多的物體? 在我的例子中,我建議它以'\\ 0'結尾。
祝你好運。
int offset = 0;
while (offset <= 1250)
{
switch (byteArray[offset])
{
case (byte)'A':
//read other data ..
offset += 5;
break;
case (byte)'B':
//read other data ..
offset += 2;
break;
case (byte)'C':
//read other data ..
offset += 50;
break;
default:
//error
break;
}
}
或二元閱讀器的另一種變體:
var reader = new BinaryReader(new MemoryStream(byteArray), Encoding.ASCII);
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
switch(reader.ReadChar())
{
case 'A':
{
var i = reader.ReadInt32();
return new TypeA(i);
}
break;
case 'B':
{
var i = reader.ReadByte();
return new TypeB(i);
}
break;
case 'C':
{
var chars = reader.ReadChars(49);
return new TypeC(new string(chars.TakeWhile(ch => ch != 0).ToArray()));
}
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.