Mit*_*nca 2 c# yield-return binaryreader binarywriter
我尝试使用 BinaryWriter 然后使用 BinaryReader 编写一些代码。当我想写时,我使用 Write() 方法。但问题是,在 Write 方法的两行之间出现了一个新字节,该字节在 ASCII 表中为十进制 31(sometines 24)。你可以在这张图片上看到它:

您可以看到索引 4 处的字节(第 5 个字节)的 ASCII 十进制值是 31。我没有在那里插入它。正如您所看到的,第一个 4 个字节是为数字(Int32)保留的,接下来是其他数据(主要是一些文本 - 现在这并不重要)。
正如您从我编写的代码中看到的: - 在第一行输入数字 10 - 在第二行文本“这是一些文本...”
第 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;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)