[Tutor] Function for converting ints from base10 to base2?

Bob Gailer bgailer at alum.rpi.edu
Thu Feb 22 01:57:56 CET 2007

David Perlman wrote:
> d'oh, I fell for the "reply-all" trick.  :)
> Here's the code in question:
> Apparently there are built in functions hex() and oct() to generate  
> hexadecimal and octal digit strings of numbers, but there's no  
> corresponding bin().  Kind of a bizarre oversight, if you ask me.
> Searching on the internet, I found this:
> def bin(integer, returnType=str):
> 	bin =  
> {'0':'000','1':'001','2':'010','3':'011','4':'100','5':'101','6':'110',' 
> 7':'111'}
> 	if returnType == int:
> 		return int(''.join([bin[i] for i in oct(integer)]))
> 	elif returnType == long:
> 		return long(''.join([bin[i] for i in oct(integer)]),10)
> 	else:
> 		return (''.join([bin[i] for i in oct(integer)])).lstrip("0")
> Just define this in the program you are writing and use bin as you
> would use oct or hex, making sure to specify int or long as the return
> type if you don't want a str.
Here's a similar function, converting characters to their ascii values 
as strings of 0 & 1. Perhaps some parts of this might be useful to 
optimize the above.

def str_to_binary(s,
  return " ".join( [bin[x]+bin[y] for x,y in [divmod(ord(c),16) for c in 

Note that by making bin a parameter it gets created one time when the 
def is executed. And indexing a list is faster than keying a dict.

Bob Gailer

More information about the Tutor mailing list