TheHidden
TheHidden

Reputation: 592

manipulate bytes down to binary levels in python

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

Upvotes: 4

Views: 3245

Answers (2)

Scott Griffiths
Scott Griffiths

Reputation: 21925

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.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798744

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

Upvotes: 2

Related Questions