gpt4 book ai didi

c# - BinaryWriter 问题 - "code adds some byte between Write() method"

转载 作者:行者123 更新时间:2023-12-05 08:35:14 28 4
gpt4 key购买 nike

我正在尝试使用 BinaryWriter 和 BinaryReader 编写一些代码。当我想写时,我使用方法 Write()。但问题是,在 Write 方法的两行之间出现了一个新字节,它在 ASCII 表中以十进制 31(sometines 24)表示。您可以在这张图片上看到它:

enter image description here

您可以看到索引 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;
}
}
}
}
}

最佳答案

如果您查看 documentation for Write(string) ,您会看到它写入了一个长度前缀字符串。所以 31 是字符串中的字符数——完全正常。

关于c# - BinaryWriter 问题 - "code adds some byte between Write() method",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7286496/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com