[Tutor] Is there an easy way to conduct binary numbers?

Orri Ganel singingxduck at gmail.com
Thu Dec 23 23:14:51 CET 2004


On Thu, 23 Dec 2004 20:42:50 +0800, Juan Shen <orion_val at 163.com> wrote:
> I have found there are easy functions and options to do basic octal and
> hexadecimal number operation.
> 
> oct(...)
> oct(number) -> string
> 
> Return the octal representation of an integer or long integer.
> 
> hex(...)
> hex(number) -> string
> 
> Return the hexadecimal representation of an integer or long integer.
> 
> print '%o' %number
> Print a decimal number in octal format.
> 
> print '%X' %number
> Print a decimal number in hexadecimal format.
> 
> However, I can't find their binary counterpart, something like bin(...)
> or print '%b'. Binary integer is extremely useful in my
> electronic-related job. So...I need help. Is there any function to
> transform between binary and decimal integers in python's library? If
> not, what's the solution to binary?
> Juan
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

Here's a possible conversion function to be used in much the same way
as oct and hex:

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.

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


More information about the Tutor mailing list