BinaryWriter问题-“代码在Write()方法之间添加了一些字节" [英] BinaryWriter problem - "code adds some byte between Write() method"
问题描述
我尝试使用BinaryWriter然后使用BinaryReader编写一些代码. 当我想写时,我使用方法Write(). 但是问题在于,在两行Write方法之间出现了一个新的字节,该字节在ASCII表中为十进制31(例程24). 您可以在这张图片上看到它:
I am try to do some code using BinaryWriter and Then BinaryReader. When I wanna write I use method Write(). But the problem is that between two lines of Write method there appears a new byte which is in ASCII table in decimal 31 (sometines 24). You can see it on this image:
您会看到索引4(第5个字节)处的字节是ASCII十进制值31.我没有在此处插入.如您所见,第1个4个字节保留给一个数字(Int32),其次是其他数据(主要是一些文本-现在这并不重要).
You can see that byte at index 4 (5th byte) is of ASCII decimal value 31. I didnt insert it there. As you can see 1st 4 bytes are reserved for a number (Int32), next are other data (some text mostly - this is not important now).
从我写的代码中可以看到: -进入第一行的数字为10 -在第二行文字这是一些文字..."
As you can see from the code i write: - into 1st line a number 10 - into 2nd line text "This is some text..."
介于这之间的第5个字节(12月31日)是怎么来的?
这是我的代码:
static void Main(string[] args)
{
//
//// SEND - RECEIVE:
//
SendingData();
Console.ReadLine();
}
private static void SendingData()
{
int[] commandNumbers = { 1, 5, 10 }; //10 is for the users (when they send some text)!
for (int i = 0; i < commandNumbers.Length; i++)
{
//convert to byte[]
byte[] allBytes;
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter bw = new BinaryWriter(ms))
{
bw.Write(commandNumbers[i]); //allocates 1st 4 bytes - FOR MAIN COMMANDS!
if (commandNumbers[i] == 10)
bw.Write("This is some text at command " + commandNumbers[i]); //HERE ON THIS LINE IS MY QUESTION!!!
}
allBytes = ms.ToArray();
}
//convert back:
int valueA = 0;
StringBuilder sb = new StringBuilder();
foreach (var b in GetData(allBytes).Select((a, b) => new { Value = a, Index = b }))
{
if (b.Index == 0) //1st num
valueA = BitConverter.ToInt32(b.Value, 0);
else //other text
{
foreach (byte _byte in b.Value)
sb.Append(Convert.ToChar(_byte));
}
}
if (sb.ToString().Length == 0)
sb.Append("ONLY COMMAND");
Console.WriteLine("Command = {0} and Text is \"{1}\".", valueA, sb.ToString());
}
}
private static IEnumerable<byte[]> GetData(byte[] data)
{
using (MemoryStream ms = new MemoryStream(data))
{
using (BinaryReader br = new BinaryReader(ms))
{
int j = 0;
byte[] buffer = new byte[4];
for (int i = 0; i < data.Length; i++)
{
buffer[j++] = data[i];
if (i == 3) //SENDING COMMAND DATA
{
yield return buffer;
buffer = new byte[1];
j = 0;
}
else if (i > 3) //SENDING TEXT
{
yield return buffer;
j = 0;
}
}
}
}
}
推荐答案
If you look at the documentation for Write(string)
, you'll see that it writes a length-prefixed string. So the 31 is the number of characters in your string -- perfectly normal.
这篇关于BinaryWriter问题-“代码在Write()方法之间添加了一些字节"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!