【问题标题】:BinaryWriter Incorrectly writing two bytes extra C#BinaryWriter 错误地额外写入两个字节 C#
【发布时间】:2020-07-13 05:33:10
【问题描述】:

首先,这是我写入指定偏移量的方法,我已经完成了调试过程,一切都得到了相应的设置。

例如,我已将 pokemonValue 设置为 190,然后将其转换为 0xBE,然后写入 offsetArray[i] == 0x1D104 处的偏移量,预期的行为是它会简单地将 0xBE 写入这个偏移量。它不这样做。而是将0x02 0x42 0x45 分别写入0x1D104 0x1D105 0x1D106

        public void writeStarterPokemon(long[] offsetArray, BinaryWriter writer, int pokemonValue)
        {
            string hexVal = "";
            for (int i = 0; i < offsetArray.Length; i++)
            {
                writer.BaseStream.Position = offsetArray[i];
                hexVal = string.Format("{0:X}", pokemonValue); // pokemonValue is a decimal ranging from 0-255;
                MessageBox.Show(string.Format("Hex val: 0x{0:1X}, Offset: 0x{1:X5}", hexVal, offsetArray[i])); // to see if the values are correct
                writer.Write(hexVal);
                writer.Flush();
            }
        }

这里是使用的数组和方法调用方式的示例

private long[] squirtleOffsets = new long[] { 0x1D104, 0x1D11F, 0x24BA5, 0x26FBC};

writeStarterPokemon(sqrtlOffsets, writer, NameList.SelectedIndex); 
// NameList is the name of my comboBox populated with pokemon data, 0-255

我已经检查了我的偏移量,它们是正确的,并且在我从它们读取的程序的早期,它按预期工作。所以我不确定为什么这不能正常工作,或者将数据设置为不正确。

【问题讨论】:

  • BinaryWriter 以字符串的长度为前缀,这就是 0x02 的来源。看起来您想要的是实际写入 BINARY 值,而不是字符串。 pokemonValue 是否总是在 0..255 范围内?
  • @MatthewWatson 好吧,这很有道理。是的,它总是在那个范围内。
  • 在这种情况下,您可以尝试writer.Write((byte)pokemonValue); - 或使用writer.BaseStream.WriteByte((byte)pokemonValue);
  • @MatthewWatson writer.BaseStream.WriteByte((byte)pokemonValue);我用过这个,它成功了,谢谢!!
  • @David 混合和匹配这样的 API 通常不是一个好主意 - 在很多情况下,你会被缓冲所困扰

标签: c# hex binarywriter


【解决方案1】:

如果要写入特定字节,则需要使用 byte[] 等 API。如果您使用Write(string) API,它会为字符串长度等编码额外的数据,这可能是您不想要的。坦率地说,BinaryWriter 在大多数情况下都不是很有用 - 您最好写信给Stream 等,这将限制您使用执行您期望的 API

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 2017-04-08
    相关资源
    最近更新 更多