tdfoster
tdfoster

Reputation: 3

Workin with binary in python

Is there an easy way to work in binary with Python?

I have a file of data I am receiving (in 1's and 0's) and would like to scan through it and look for certain patterns in binary. It has to be in binary because due to my system, I might be off by 1 bit or so which would throw everything off when converting to hex or ascii.

For example, I would like to open the file, then search for '0001101010111100110' or some string of binary and have it tell me whether or not it exists in the file, where it is, etc.

Is this doable or would I be better off working with another language?

Upvotes: 0

Views: 117

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308206

To convert a byte string into a string of '0' and '1', you can use this one-liner:

bin_str = ''.join(bin(0x100 + ord(b))[-8:] for b in byte_str)

Combine that with opening and reading the file:

with open(filename, 'rb') as f:
    byte_str = f.read()

Now it's just a simple string search:

if '0001101010111100110' in bin_str:

Upvotes: 4

James
James

Reputation: 2795

You would be better working off another language. Python could do it (if you use for example, file = open("file", "wb")

(appending the b opens it in binary), and then using a simple search, but to be honest, it is much easier and faster to do it in a lower-level language such as C.

Upvotes: 0

Related Questions