Convert an Integer to a Binary Representation

Here is a quick way to convert any integer n into a string that represents the n integer in binary notation:

def dec_to_bin(n, bits=32):
    return ''.join([str((n >> y) & 1) for y in range(bits - 1, -1, -1)])

What's going on in the above code? This can be better explained if we read the return line in the dec_to_bin function backwards. First we create a list of integers from 31 to 0 in order to iterate through it. This list is created with the built-in range function and it uses the number of bits that we passed into the function, with a default being 32. Next, we iterate through the list with each number being represented by y. Then we take the number parameter n, which is the number we want to transform to binary, and we shift its bits to the right by y places. Then we apply a bitwise and operation on the result of that right shift and the literal value of 1. This and operation tells us if the bit at location y is turned on or off. We then make a string out of the value and append it to the string that we are building to return to the user. This is a perfect example of Python's conciseness and the power of list comprehensions.

You can use the code above like so:

>>> print dec_to_bin(255)
00000000000000000000000011111111

Enjoy!

Comments

Comments powered by Disqus