Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 二进制读取器通过填充字节数组使我不知所措_C#_.net - Fatal编程技术网

C# 二进制读取器通过填充字节数组使我不知所措

C# 二进制读取器通过填充字节数组使我不知所措,c#,.net,C#,.net,所以我有一个非常简单的代码,它读取一个文件,并以十六进制查看器的方式输出它的数据。这是: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace HexViewer { class Program { static void Main(string[] args) {

所以我有一个非常简单的代码,它读取一个文件,并以十六进制查看器的方式输出它的数据。这是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace HexViewer
{
    class Program
    {
        static void Main(string[] args)
        {
            BinaryReader br = new BinaryReader(new FileStream("C:\\dump.bin", FileMode.Open)); 
            for (int i = 0; i < br.BaseStream.Length; i+= 16)
            {
                Console.Write(i.ToString("x") + ": ");
                byte[] data = new byte[16];
                br.Read(data, i, 16);
                Console.WriteLine(BitConverter.ToString(data).Replace("-", " "));
            }
            Console.ReadLine();
        }
    }
}
字节数组填充16个字节,然后填充文件第15字节到第31字节的数据。因为它无法将32个字节放入16字节的大数组中,所以会引发异常。您可以对任何大于16字节的文件尝试此代码。所以,问题是,这个代码怎么了?

只需更改
br.Read(数据,i,16)
br.读取(数据,0,16)

您每次都在读取一个新的数据块,因此无需对
数据
缓冲区使用
i

更好的是,改变:

byte[] data = new byte[16];
br.Read(data, 0, 16);
致:


我要说
br.Read(data,I,16)
中的
I
。这不应该是
0
?我同意@DeCaf。索引不引用要读取的数据,而是引用输出数组中的索引。在这种情况下,数据应始终写入输出数组的开头,因此值应为0。谢谢!它现在工作得很好!我我真不敢相信它起作用了。但是索引是从文件的开头开始的,Read()不使用Stream.Position,对吗?对吗?Read()使用它的内部流位置,所以不需要跟踪它。您只需要
i
即可记录控制台输出中的当前位置,就像您正在做的那样。
index
参数是要开始读取的数组中的第一个索引。
byte[] data = new byte[16];
br.Read(data, 0, 16);
var data = br.ReadBytes(16);