7

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)

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;
}

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?

2 Answers2

18

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)

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.

Scott Griffiths
  • 21,438
  • 8
  • 55
  • 85
-2

Try this:

my_num = int(f.read(1))

And then xor the number stored in my_num.

bstamour
  • 7,746
  • 1
  • 26
  • 39
  • -1 The question was how to modify the value of the byte. `int()` will try to convert a string of digits to a number which is not at all the same thing. – Duncan Feb 18 '11 at 08:16