Welcome, guest | Sign In | My Account | Store | Cart

This is a very simple look-up based method for converting integer to binary string. In my tests, using 'timeit', its the fastest around. And with increasing value of input decimal number, it surpases any 'run time computation' based method doing the above.

Python, 15 lines
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 hexDict = { '0':'0000', '1':'0001', '2':'0010', '3':'0011', '4':'0100', '5':'0101', '6':'0110', '7':'0111', '8':'1000', '9':'1001', 'a':'1010', 'b':'1011', 'c':'1100', 'd':'1101', 'e':'1110', 'f':'1111', 'L':''} def dec2bin(n): """ A foolishly simple look-up method of getting binary string from an integer This happens to be faster than all other ways!!! """ # ========================================================= # create hex of int, remove '0x'. now for each hex char, # look up binary string, append in list and join at the end. # ========================================================= return ''.join([hexDict[hstr] for hstr in hex(n)[2:]])

Charlie Clark 14 years, 9 months ago

Is this anything related to http://code.activestate.com/recipes/219300/ ? If so it might be better to continue the discussion over there. Apart from that I think you're right that it is a silly approach: int -> hex -> list -> concatenation. This might be faster on individual lookups but if you have lots of numbers to convert anything that can convert in a single pass should be faster and actually the integer is only a representation of the underlying binary value.

Gabriel Genellina 14 years, 9 months ago

>>> bin(123)
'0b1111011'
>>> bin(123)[2:]
'1111011'
Vishal Sapre (author) 14 years, 9 months ago

@Gabriel: I would love to use the built-in bin(), but thats not available on my 2.5 box. We cannot move to 2.6 just as yet...and so had to come up with this one.

@Charlie: You are true, this is very good for conversion once in a while...like if you are in a big loop and you happen to recieve an int, and want to display its binary representation. I had looked at the the recipie you've referred to, but everything there was based on runtime computation..so thought of creating a new recipie.

 Created by Vishal Sapre on Fri, 17 Jul 2009 (MIT)

### Required Modules

• (none specified)