I need to convert from an integer to a list of size 8 that is the binary representation of that number (number <= 255) and back. Currently I am using these lines
list(bin(my_num)[2:].rjust(8,'0'))
int("".join(my_list),2)
I did some googling, but had a hard time finding relevant information. I’m just curious if there is a faster, or more standard way to do this.
edit:
Would using bit masking make it faster. E.g. something like this
[(my_num>>y)&1 for y in xrange(7,-1,-1)]
Like I mentioned in a comment I am using this for a steganography app I am writing, so I am doing this thousands of times (3 times per pixel in an image), so speed is good.
In Python 2.6 or newer, use
formatsyntax:One of the neat things about Python strings is that they are sequences. If all you need to do is iterate through the characters, then there is no need to convert the string to a list.
Edit: For steganography, you might be interested in converting a stream of characters into a stream of bits. Here is how you could do that with generators:
And to convert a stream of bits back into a stream of characters:
For example, you could use the above functions like this:
Also, SO guru Ned Batchelder does some steganography-related experiments using Python and PIL here. You may be able to find some useful code there.
If you find you need more speed (and still want to code this in Python), you may want to look into using numpy.