4

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())

Community
  • 1
  • 1
TheHidden
  • 551
  • 1
  • 8
  • 20
  • what python version are you using? Strings are an abstraction. Make sure you understand what encoding is and how it works. See [this tutorial](http://farmdev.com/talks/unicode/) and [this one](http://www.diveintopython3.net/strings.html) – Pynchia Sep 25 '15 at 10:26
  • 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 – TheHidden Sep 25 '15 at 10:42

2 Answers2

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')
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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.

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