【问题标题】:Read hex data from a file, starting at position x, terminating at first null byte (00)?从文件中读取十六进制数据,从位置 x 开始,在第一个空字节 (00) 处终止?
【发布时间】:2015-12-26 22:14:46
【问题描述】:

所以我需要读取一个包含十六进制“单词”的文件(ACSII)。当然,单词可以是任意长度,但总是从偏移量 0x1290 开始。我想要做的是读取从偏移量 0x1290 开始的文件的十六进制,并继续直到它遇到一个空字节(00)。到目前为止,我尝试过的所有编码似乎都需要固定长度才能读取。

filePath = "C:\myfile"
BinaryReader reader = new BinaryReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None));
reader.BaseStream.Position = 0x1290;     // The starting offset
byte[] word = reader.ReadBytes(); // Must specify length within ReadBytes(e.g. 0x99)
reader.Close();`

在所需的“字”之后通常可以有其他不需要的十六进制数据,但是在“字”之后总是有一个空字节。这就是为什么我不能指定长度。

【问题讨论】:

  • 但是问题是什么?如果您需要读取多个字节直到达到 0 字节,为什么不能一次从文件中读取一个字节?
  • 你能帮我解决这个问题吗?我对 c# 很陌生。我想我需要某种循环,但我不能使用 byte[] 数组?我还打算将十六进制字符串转换为文本字符串进行显示

标签: c# .net c#-4.0 hex filereader


【解决方案1】:

使用while循环:

filePath = "C:\myfile"
BinaryReader reader = new BinaryReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None));
reader.BaseStream.Position = 0x1290;
byte char;
byte[] result=new byte[length_of_the_word];
int i=0;

while(((byte)char=reader.Read())!=-1)
{
   result[i++]=char;
}

reader.close();

然后将 -1(文件结尾)替换为十六进制结束字,例如 0x00

【讨论】:

  • 你是什么意思[length_of_the_word],因为长度可以是任何东西?
  • 如果搜索词的长度是固定的,则将其作为数组的长度,否则将搜索词的最大长度放入
【解决方案2】:

如果您不知道字符串的长度是多少个字符,您应该使用某种不需要预先存储确切数据长度的集合。这似乎是List<byte> 的完美作品

List<byte> bits = new List<byte>();
using(FileStream s = new FileStream(@"C:\myfile", FileMode.Open))
using (BinaryReader reader = new BinaryReader(s))
{
    reader.BaseStream.Position = 0x1290;
    while (reader.PeekChar() != -1)
    {
        byte b = reader.ReadByte();
        if(b != 0x00)
            bits.Add(reader.ReadByte());
    }
    string result = Encoding.UTF8.GetString(bits.ToArray());
}

【讨论】:

    【解决方案3】:

    谢谢大家,我尝试了上述方法,但他们似乎不断出现错误。无论如何,我自己想出了一个循环,并在这里分享:

    int c = 0;
    int runs = 0;
    byte[] data = new byte[400]; // byte array setup
    
    // read hex values (loop) and convert to acsii string
    BinaryReader reader = new BinaryReader(new FileStream("C:\File", FileMode.Open, FileAccess.Read, FileShare.None));
    reader.BaseStream.Position = 0x1290;
    
    while (c == 0)
    {
        data[runs] = reader.ReadByte();
        if (data[runs] == 0x00)
        {
           c = 1; // stop loop at .ReadByte = 0x00
        }
        runs++;
    }
    reader.Close();
    
    // hex to acsii string, removing null bytes
    result = Encoding.Default.GetString(data.Where(x => x != 0).ToArray());
    

    看起来效果不错

    【讨论】:

    • Encoding.Default不是 ASCII。如果需要 ASCII,请使用 Encoding.ASCII。如果没有,请弄清楚您实际需要什么编码,否则您将遇到麻烦。另请注意,您可以使用break; 退出循环。还有一个bool 类型对于“循环变量”来说是一个更好的选择。 Encoding.GetString 有一个参数来表示您要解码的字节数 - 请尝试使用 Encoding.ASCII.GetString(data, 0, runs - 1);
    猜你喜欢
    • 2022-01-17
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    相关资源
    最近更新 更多