1

I seem to be able to find information on how to do this in C#, but not on how to perform the same operation in Python.

Any advice or suggestions would be appreciated. Thank you very much.

  • 4
    This would of course apply to any kind of file, not just exe files. Or do you want to extract a specific piece of the exe file? –  Sep 13 '11 at 20:32

4 Answers4

4
def padded_bin(number, width=8, padchar='0'):
    return bin(number)[2:].rjust(width, padchar)

with open(r'C:\path\to\file.txt', 'rb') as f:
    as_binary = ''.join(padded_bin(ord(c)) for c in f.read())
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
2
''.join((map(''.join, itertools.product(*['01']*8))[ord(c)]
         for c in open('foo').read()))
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
  • I completely forgot about `bin`, and I couldn’t resist terse and unreadable. – Josh Lee Sep 13 '11 at 21:45
  • 1
    Actually a look up table wouldn't be that bad in this case. However it would be bad if you recalculate that table for every character in your file. ;) – Jeff Mercado Sep 14 '11 at 05:27
0
print "".join(bin(ord(c))[2:] for c in file("a.exe", "rb").read())

update with padding:

print "".join(("00000000"+bin(ord(c))[2:])[:8] for c in file("a.exe", "rb").read())
rocksportrocker
  • 7,251
  • 2
  • 31
  • 48
0

Use open with 'rb' as flags. That would read the file in binary mode

Facundo Casco
  • 10,065
  • 8
  • 42
  • 63