3

I am trying to start learning about writing encryption algorithms, so while using python I am trying to manipulate data down to a binary level so I can add bits to the end of data as well as manipulate to obscure the data.

I am not new to programming I am actually a programmer but I am relatively new to python which is why I am struggling a bit.

can anyone show me the best way to manipulate, in python, a string down to the binary level (or recommend in what way I should approach this). I have looked at a number of questions:

Convert string to binary in python

Manipulating binary data in Python

Convert binary to ASCII and vice versa

But all these are not what I am looking for and I do not know enough of python to be able to pick out what I need. can someone please assist me with details (if you use a function please explain what it is to me e.g. ord())

2
  • what python version are you using? Strings are an abstraction. Make sure you understand what encoding is and how it works. See this tutorial and this one Commented Sep 25, 2015 at 10:26
  • 1
    i am using 3.5 and yes I understand how encoding works, dont worry about that. I am a primarily a PHP and MySQL developer encoding is the bane of my existence Commented Sep 25, 2015 at 10:42

2 Answers 2

2

Take a look at the bitstring module, which is designed to make binary manipulation as easy as possible.

from bitstring import BitArray
a = BitArray('0xfeed')    # 16 bits from hex
a += '0b001'              # Add three binary bits
a.replace('0b111', '0b0') # Search and replace
a.count(1)                # Count one bits

It has a full manual and lots of examples.

Sign up to request clarification or add additional context in comments.

2 Comments

I got the results returned as 3 and 5 (5 on the count) why is this? 3 i am guessing is the x=n instances replaced?
Yes the 3 is the number of replacements done. Try a.bin to look at the binary representation at any time.
2

bitarray lets you treat bit sequences as normal Python sequences and to operate on them as binary values.

>>> bitarray.bitarray('0101') | bitarray.bitarray('1010')
bitarray('1111')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.