Is there a better way to convert from decimal to binary in python? -
I have to convert from a whole number to a list of size 8 which is the binary representation of that number (number & lt; = 255 ) and return. Currently I am using these lines
list (bin my_num) [2:]. Rjust (8, '0')) int ("". (My_list) , 2)
I did some googling, but there was a hard time finding relevant information. I'm just curious if there's a faster or more standard way to do this.
Edit: Using bit masking will make it faster like something like
Xrange (7, -1, -1) ) In [[my_num & gt; Y) & amp; 1]
Like I mentioned in the comment that I am writing this, I am using it for a Steganography app, so I have been using this thousands of times (3 pixels in a pixel) I am doing so, so the speed is good.
In Python 2.6 or new, use format
:
'{0: 0 = # 10b}'. Format (my_num) [2:] # '00001010'
One of the clearer things about dragon strings is that they are visible. If you only want to repeat through letters, there is no need to change the string to the list.
Edit : For steganography, you may be interested in converting a stream of bits into a stream of characters here but here is how you do this with the generator Def str2bits (astr): around astr: '{0: 0 = # 10b}' for the n = ord (char) for the form .format (n) [/ b] 2:]: yield int (bit)
and to convert a stream of bits back into a stream of letters:
DfGrouper ( N, Iterable, Falval = None ): # Source: http://docs.python.org/library/itertools.html#recipes "Grouper (3, 'ABCDFG,' X) -> ABC DEF Gxx" return itertools.izip_longest (* [Iter (iterable)] * n, fillvalue = fillvalue) def bits2str (bits): b for grouper (8, bits): yield kr (int (''. 'For example, you can use this kind of work Can be: in str2bits for b ('hi zwurburg'): print b, # 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 0 0 1 1 1 0 1 1 0 0 1 1 1 0 0 0 1 0 1 1 1 0 0 1 0 0 1 1 0 0 0 1 0 0 1 1 0 0 0 0 1 0 1 1 1 0 0 1 0 0 1 1 0 0 1 1 1 # Beats 2 Stratus Str2bits Inversion: Print ''. Which Other than this, some SOG masters use dragon experiments related to some steganography, and PIL will be there for you (p [c] bits2str (str2bits ('hi zvarberg')) # hi zwurburg
Can find some useful codes.
If you think that you need to speed up (and still have to code it in Python), then you can check to use it.
Comments
Post a Comment