【问题标题】:Read input file in hex mode in C#在 C# 中以十六进制模式读取输入文件
【发布时间】:2014-11-09 04:39:15
【问题描述】:

文件信息:前 4 个字节包含文件中的记录数 |接下来的 4 个字节包含第一条记录的长度。在第一次记录之后 4 个字节包含第二个记录的长度。整个文件是这样的。所以我必须读取输入文件并跳过前 4 个字节。之后我需要读取 4 个字节,这将为我提供即将到来的记录的长度,并以字符串形式写出记录并重复该过程。

我没有得到我应该得到的东西。例如: 对于 7F CB 00 00,我应该得到 32715(我不需要,需要跳过)。接下来的 4 个字节是 00 D3 00 00 00 我应该得到 211,但我没有得到。

任何帮助将不胜感激。

private void button1_Click(object sender, EventArgs e)
    {
        FileStream readStream;
        readStream = new FileStream(singlefilebox.Text,FileMode.Open,FileAccess.Read);
        BinaryReader readBinary = new BinaryReader(readStream);


        byte inbyte;
        inbyte = readBinary.ReadByte();
        string outbyte;
        while (readBinary.BaseStream.Position < readBinary.BaseStream.Length)
        {
            inbyte = readBinary.ReadByte();
            outbyte = Convert.ToString(inbyte);
        }

【问题讨论】:

  • 代码的实际输出是什么?与预期结果进行比较有助于找出问题所在
  • 字节顺序可能不会像你想象的那样解释:en.wikipedia.org/wiki/Endianness
  • 20300021100127241241 for 7F CB 00 00 00 D3 00 00 7F F1 F1 F1 F5 F8 F4 F3 7F....

标签: c# byte filestream binaryreader


【解决方案1】:

第一个问题是您如何进行输出。当您生成外字节时,它会被转换为十进制表示法。比如CB转换为203。

将生成外字节的行更改为以下内容:

outbyte = Convert.ToString(String.Format("{0:X}", inbyte));

这会打印十六进制数字的字符串表示形式。

有关字符串格式的更多详细信息,请参阅此答案。 String.Format for Hex

更大的问题是您需要以正确的方式组合字节。您需要读取每个字节,将其移动 8 位,然后添加下一个字节。

        string fileName = @"..\..\TestInput.hex";
        FileStream readStream;
        readStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        BinaryReader readBinary = new BinaryReader(readStream);

        byte inbyte;
        string outbyte;
        int value;

        inbyte = readBinary.ReadByte(); // read in the value: 7F in hex , 127 in decimal
        value = inbyte << 8; // shift the value 8 bits to the left: 7F 00 in hex, 32512 in decimal
        inbyte = readBinary.ReadByte(); // read in the next value: CB in hex, 203 in decimal
        value += inbyte; // add the second byte to the first: 7F CB in hex, 32715 in decimal
        Console.WriteLine(value); // writes 32715 to the console

【讨论】:

  • 我明白你的意思。但是,我想要另一种方式。我想将输入读取为 '7F CB 00 00' 给我一个 32715 的输出。我的问题是当我停在 inbyte = readBinary.ReadByte();我得到 127 的 7F 和 203 的 CB。相反,我想先得到 7F,然后再在 outbyte = Convert.ToString(inbyte); 将其转换为字符串
  • 我不完全确定你在问什么。在我的代码末尾,值设置为 32715。0x7f = 127 和 0xCB = 203。要获得 32715 的输出字节,您需要有 0x7FCB。 0x7F 是高位字节。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 2013-07-07
  • 2013-09-12
  • 2020-10-25
  • 1970-01-01
  • 2014-03-30
  • 2015-05-01
相关资源
最近更新 更多