To convert a decimal number to a binary number in python without using the built-in bin()
function, you can use bitwise operators and integer division.
Here is an example code snippet:
main.py205 chars11 lines
In the above code, dec_to_bin()
function takes a decimal number as input and returns its binary equivalent in string format. It first checks if the input number is 0 or not. If it is 0, then it returns '0', else it initializes an empty string called result
.
Inside the while loop, %
operator is used to get the remainder of num
when it is divided by 2. The remainder is then converted to a string using str()
function and added to the left of the result
string. After that, num
is divided by 2 using integer division //
to discard the remainder and update its value.
Finally, the function returns the result
string which contains the binary representation of the input decimal number.
You can call this function with any decimal number as its argument to get its binary representation as output.
gistlibby LogSnag