0

I am looking to see if there is a way to automatically do a 1s compliment or flip the bits in a file or files. I have managed to open a file in binary using the syntax "file=open('001.a','rb')" and then searching through stack overflow found a while loop to iterate.

When I assign a variable to the read portion of the file so for eg. a = file.read() and then do type on a[1] it appears as type 'str'.

I am confused as If I opened this file as a binary file then shouldn't everything be shown in 1's and 0's.

Sorry am really new to programming and am totally lost. I have searched through and looked at a lot of examples but none of them appear to give a complete solution and picking and mixing code from different posts is not working as I keep getting type errors. I tried using struct but just do not understand the syntax or what is it supposed to achieve.

I would think that I need to convert that string to a binary of 1's and 0s and then somehow flip all 0's to 1 and 1 to 0's but it seems to be easier said then done.

a[:10] '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'

Thanks

Ivan Kolesnikov
  • 1,787
  • 1
  • 29
  • 45
Ned
  • 1

1 Answers1

0

Would something like this do:

with open("/tmp/xyzzy.tmp", "rb") as fp:
    q = fp.read()

nf = open("/tmp/xyzzy.new", "ab")    
for i in q:
    newbyte = ord(i) ^ 255
    nf.write(chr(newbyte))   

nf.close()

It just rotates through your data byte by byte and flips bits as it goes.

Hannu
  • 11,685
  • 4
  • 35
  • 51
  • Thank you so much for that. I will try it in a bit. I just have 2 questions. 1) When you open the file with "rb" it is supposed to open in binary. I take that to mean that if you print q then it should print the 0's and 1's but it seems that it is not doing that. Shouldn't the file be in binary. I am using python 2.7 2) It seems that the variable q is assigned to read the entire file then how does it work on a byte. I mean if you print q it will print out the entire file. – Ned Jul 25 '17 at 22:52
  • The above code is not working for me. When I type nf.close() it gives a syntax error:invalid syntax in idleFile "", line 4 with a pointer on nf.close(). Tx – Ned Jul 25 '17 at 23:08
  • https://stackoverflow.com/questions/9644110/difference-between-parsing-a-text-file-in-r-and-rb-mode this is an explanation of binary mode. – Hannu Jul 26 '17 at 10:50
  • The syntax error is just a copy paste problem, as there was not a line feed after for loop and nf.close(). If you copypaste to python, you need a line feed to break the for loop indention. Try it now. The original worked as well if ran as a script. – Hannu Jul 26 '17 at 10:54