C# 在C语言中以十六进制模式读取输入文件

C# 在C语言中以十六进制模式读取输入文件,c#,byte,filestream,binaryreader,C#,Byte,Filestream,Binaryreader,文件信息:前4个字节包含文件中的记录数|后4个字节包含第一条记录的长度。在第一条记录之后,4个字节包含第二条记录的长度。整个文件是这样的。因此,我必须读取输入文件并跳过前4个字节。之后,我需要读取4个字节,这将给我即将到来的记录长度,并写出字符串记录,并重复这个过程 我没有得到我应该得到的。例如: 对于7F CB 00,我应该得到32715,我不需要,需要跳过。接下来的4个字节是 00 D3 00 00 00 00我应该得到211,但我没有得到 任何帮助都将不胜感激 private void b

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

我没有得到我应该得到的。例如: 对于7F CB 00,我应该得到32715,我不需要,需要跳过。接下来的4个字节是 00 D3 00 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);
        }

第一个问题是如何进行输出。当您生成outbyte时,它将被转换为十进制表示法。例如,CB转换为203

将生成outbyte的行更改为以下内容:

outbyte = Convert.ToString(String.Format("{0:X}", inbyte));
这将打印十六进制数的字符串表示形式

有关字符串格式的更多详细信息,请参见此答案

更大的问题是需要以正确的方式组合字节。您需要读入每个字节,将其移位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

代码的实际输出是什么?与预期结果进行比较有助于找出哪些是错误的字节顺序可能不会按您认为的方式进行解释:203000211001127241241对于7F CB 00 00 00 00 D300 00 7F F1 F1 F1 F5 F8 F4 F3 7F…我明白您的意思。然而,我想要另一种方式。我想把输入读作“7F CB 00 00”,给我32715的输出。我的问题是当我停在inbyte=readBinary.ReadByte;我得到127的7F和203的CB。相反,我希望先得到7F,然后在outbyte=convert.ToStringinbyte处将其转换为字符串;我不完全确定你在问什么。在代码末尾,值设置为32715。0x7f=127和0xCB=203。要获得32715的outbyte,您需要有0x7FCB。0x7F是高阶字节。