本文介绍了将每个字节与0x71异或的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从文件中读取一个字节,将其与0x71进行异或,然后将其写回到另一个文件中.但是,当我使用以下命令时,它只是将字节读取为字符串,因此异或会产生问题.

I needed to read a byte from the file, xor it with 0x71 and write it back to another file. However, when i use the following, it just reads the byte as a string, so xoring creates problems.

f = open('a.out', 'r')
f.read(1)

所以我最终在C语言中做了同样的事情.

So I ended up doing the same in C.

#include <stdio.h>
int main() {
  char buffer[1] = {0};
  FILE *fp = fopen("blah", "rb");
  FILE *gp = fopen("a.out", "wb");
  if(fp==NULL) printf("ERROR OPENING FILE\n");
  int rc;
  while((rc = fgetc(fp))!=EOF) {
    printf("%x", rc ^ 0x71);
    fputc(rc ^ 0x71, gp);
  }
  return 0;
}

有人可以告诉我如何将使用 f.read()获得的字符串转换为十六进制值,以便我可以将其与0x71进行异或,然后将其写入文件中?

Could someone tell me how I could convert the string I get on using f.read() over to a hex value so that I could xor it with 0x71 and subsequently write it over to a file?

推荐答案

如果要将某事物视为字节数组,则通常需要一个 bytearray ,因为它表现为一个可变的数组.字节:

If you want to treat something as an array of bytes, then usually you want a bytearray as it behaves as a mutable array of bytes:

b = bytearray(open('a.out', 'rb').read())
for i in range(len(b)):
    b[i] ^= 0x71
open('b.out', 'wb').write(b)

索引字节数组将返回一个介于0x00和0xff之间的整数,并且就地进行修改避免了创建列表并将所有内容重新合并的麻烦.还要注意,文件是以二进制('rb')打开的-在您的示例中,您使用'r'并不是一个好主意.

Indexing a byte array returns an integer between 0x00 and 0xff, and modifying in place avoid the need to create a list and join everything up again. Note also that the file was opened as binary ('rb') - in your example you use 'r' which isn't a good idea.

这篇关于将每个字节与0x71异或的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:29