首页 > 解决方案 > 如何从 c# 中的已知偏移量读取 4、6、8 个字节?

问题描述

文件偏移 | 值:
0x2274 = 0F
0x2276 = 63

我正在尝试读取偏移量 2274 到 2276;但是,它没有正确读出。

//read Binary
BinaryReader br = new BinaryReader(File.OpenRead(filepath));

//Name Change
long nameoffset = Convert.ToInt64(0x2274, 16);
br.BaseStream.Position = nameoffset;
namevalues = br.ReadByte().ToString("X4");

string GetName = Convert.ToString("NameChg");
if (GetName == "NameChg")
{

    long myvalue = Convert.ToInt64(namevalues, 16);
    MessageBox.Show("Current Name: " + Convert.ToString(myvalue));
}

结果返回为“0015”。我需要将结果返回为“25359”。

标签: c#

解决方案


解决我自己的难题。这两天我都纳闷了。下面是我的代码示例,适用于任何想要这样做的人。如果您知道缩短这些代码的更好方法;随意张贴。

        //This is where you'll code to load the binary file.
        var filepath = Path.Combine(Directory.GetCurrentDirectory(), "Test.bin");

        //read Binary
        BinaryReader br = new BinaryReader(File.OpenRead(filepath));
        string namevalues = null;
        //test offset purposes
        for (int i = 0x2274; i <= 0x2276; i++)
        {
            br.BaseStream.Position = i;
            namevalues += br.ReadByte().ToString("X2");

        }
        br.Close();

        //put binary hex to array
        string newStr = System.Text.RegularExpressions.Regex.Replace(Convert.ToString(namevalues), ".{2}", "$0,");
        newStr = newStr.TrimEnd(',');
        string[] NewBytes = newStr.Split(',').ToArray();

        //Reverse order in Array
        Array.Reverse(NewBytes);
        newStr = NewBytes[0] + NewBytes[1] + NewBytes[2];
        int decValue = Convert.ToInt32(newStr, 16);
        String decValue2 = Convert.ToString(decValue);

        //test output
        messagebox.show(decValue2);

推荐阅读