将字节读入数组,然后将结果异或为字符串

Read bytes into array then xor the result into a string

我读取字节并将它们显示在文本框中:

BinaryReader br = new BinaryReader(File.OpenRead(path));
br.BaseStream.Position = 0x1D; 
textBox1.Text = br.ReadInt32().ToString("X");
br.Dispose();

我需要读取 4 个字节,然后将每个字节与值 149 进行异或运算,并将结果打印到文本框中。文本框好像只显示"System.Byte()"

我试过这段代码,但有很多错误,例如无法将字节转换为整数:

BinaryReader br = new BinaryReader(File.OpenRead(path));
br.BaseStream.Position = 0x3E8;
byte[] buffer = br.ReadBytes(4);
int i = 149;

输出应如下所示:

result = buffer[0] ^ 149;
result2 = buffer[1] ^ 149;
result3 = buffer[2] ^ 149;
result4 = buffer[3] ^ 149;

我怎样才能做到这一点?

你需要这样的东西:

using (var br = new BinaryReader(File.OpenRead(path)))
{
    br.BaseStream.Position = 0x1D;
    byte[] bytes = br.ReadBytes(4);

    for (int i = 0; i < 4; i++)
    {
        bytes[i] = (byte)(bytes[i] ^ 149);
    }

    textBox1.Text = new string(bytes.Select(Convert.ToChar).ToArray());
}

欢迎来到 Stack Overflow,这是梦想成真的土地(如果您的梦想是回答编程问题。)。由于这是您的第一个问题,我会尽力回答,但在未来,请尝试遵循社区指南以基本表明

  1. 您已经尝试过自己解决问题,
  2. Post 适用于您的问题的所有代码,并且
  3. 明确说明为什么您发布的代码没有按您希望的方式执行

作为旁注,当您想要快速测试小程序时,请查看 dotnetfiddle.net。专业提示:不要使用 excel 调试 C# 程序 ;)

答案:每日双倍

好的,我将推断您的问题如下。我知道非常自由的解释,但我想在这里帮助你

[How can I read 4 bytes from a file at a given file offset, XOR each of those 4 bytes with 0x149, then display those on the screen?]

好的,我认为首先要获得一个 FileStream 对象。更多阅读:what is using?

using (var input = File.OpenRead(path))
{
    // somehow seek to file offset
    // read 4 bytes, and
    // XOR each byte with 0x149
    // store results in a List<byte> (or something)
}

// display result

好的,要查找文件,您需要input.Seek(0x1D, SeekOrigin.Begin);(假设OP中的0x1D是正确的)。

要读取 4 个字节,请执行此操作(请参阅 ReadByte() 文档)

for (var i=0;i<4;i++){
    var byteThatIsNotRemembered = input.ReadByte();
}

现在你需要用

异或那些字节
for (var i=0;i<4;i++){
    var byteThatIsNotRemembered = input.ReadByte() ^ 0x149;
}

最后,将它们保存到list

// need to instantiate list somewhere near top
var byteList = new List<byte>();

// ... other code that we've written

for (var i=0;i<4;i++){
    var byteThatIsRememberedNow = input.ReadByte() ^ 0x149;

    // need to cast to byte because ^ operator creates ints
    byteList.Add((byte) byteThatIsRememberedNow);
}

// you'll need to replace this with something for your text box...
// couldn't figure out from your question
for (var i=0;i<byteList.Length;i++){
    Console.WriteLine(byteList[i]);
}

现在一起...

// need to instantiate list somewhere near top
var byteList = new List<byte>();

using (var input = File.OpenRead(path))
{
    input.Seek(0x1D, SeekOrigin.Begin);
    for (var i=0;i<4;i++){
        var byteThatIsRememberedNow = input.ReadByte() ^ 0x149;
        byteList.Add((byte) byteThatIsRememberedNow);
    }
}

// you'll need to replace this with something for your text box...
// couldn't figure out from your question
for (var i=0;i<byteList.Length;i++){
    Console.WriteLine(byteList[i]);
}

这是一个类似的 dotnetfiddle,我使用字符串而不是文件来生成流。

如果有帮助请告诉我