I want to know how to convert a decimal integer into its binary form??

I came across a code which used BIT OPERATORS; I could not understand it.


Note: This is not my ASSIGNMENT PROBLEM. I know one way of converting decimal into binary and the code is as below..

binary = 0

while decimal != 0:
bit = decimal % 2
binary = bit + (10 * binary)
decimal = decimal / 2

I want to know the other way using BIT operator and thats why I have posted this query.
Thanks in advance.

To HIM you shall return.

Take a look at this Python code snippet at:
It uses a bitwise shift right operator to get the binary representation of an integer.

Editor's note:
I think we lost the reference when snippets were folded into the regular forum. Looks like Ene refers to ...

def denary2binary(n):
    '''convert denary integer n to binary string bStr'''
    bStr = ''
    if n < 0:  raise ValueError, "must be a positive integer"
    if n == 0: return '0'
    while n > 0:
        bStr = str(n % 2) + bStr
        n = n >> 1
    return bStr

# test
print(denary2binary(255))  # 11111111
print(denary2binary(128))  # 10000000
print(denary2binary(127))  # 1111111
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.