Binary Representation of Numbers in Python
Posted on July 2nd, 2008 in Python |
Over the last few months I’ve found myself playing with binary numbers a great deal - for investigating various algorithms, for working out bit masks, for understanding bit-twiddling operations (such as using xor for clearing a register in assembly language), etc. At the moment, I’m predominantly a Python user (I love the clean syntax, the power and speed, and the compatibility with C), but I’ve found no easy way of representing numbers in binary form in Python (or indeed in any other language).
Clearly the ability to represent numbers in binary form would have little practical use in a programming language, but for purely academic reasons I decided to write a very basic binary class in Python. At the moment it only supports positive integers (its just plain base 2, not two’s complement), and is limited in its range of features, but I have found it to useful on occasion (mostly when using Python in the command line mode).
class Bin(object): def __init__(self, num): num = str(num) if [d for d in num if int(d) > 1]: raise(TypeError, 'not a binary number') self.__num = self.__bin_str_to_int(num) def __bin_str_to_int(num): return sum(2**n for n in range(len(num)) if int(num[-n-1])) def __get_bin_str(self): binstr = '' n = self.__num while n > 0: binstr = str(n % 2) + binstr n /= 2 return binstr def __int__(self): return self.__num def __repr__(self): return str(self.__bin_str) __bin_str = property(fget=__get_bin_str)
Here is an example of its basic usage:
>>> from bintype import Bin >>> x = Bin(11001100) >>> x 11001100 >>> int(x) 204
In it’s current state it is of little use, but with some simple operator overloading (__add__, __lshift__, etc.) and support for negative numbers using two’s complement it could provide a useful way of testing basic operations on binary integers.
2 Responses
Why not inherit from int rather than object? Seems to me you’d get most of your arithmetic operations for free, and you’d only have to override __repr__().
Also, Python 3 will have special syntax for declaring numbers in binary, like this: 0b11001100. See PEP-3127 for details.
I had a go at inheriting from int but had some trouble - I couldn’t find where the data was stored. As it’s a builtin type I couldn’t find a way to preserver all functionality except for one or two methods…
I hadn’t seen that PEP, that is a much better solution!