To convert decimal numbers to binary, use the decimalToBinary function to divide the number by 2, collect remainders and reverse the order. To convert binary to decimal, use the binaryToDecimal function to multiply each binary digit by 2 raised to the power of its position and sum the results.
To convert a decimal number to binary and vice versa in Python, we can write two functions, decimalToBinary and binaryToDecimal.
For decimalToBinary function, we repeatedly divide the decimal number by 2 and store the remainder in a string in reversed order. Here's a step-by-step Python code that accomplishes that:
def decimalToBinary(num):
bits = ''
while num > 0:
bits = str(num % 2) + bits
num = num // 2
return bits
For the binaryToDecimal function, we iterate over the binary string in reversed order, multiply each digit by 2 raised to the power of its position, and sum it all up. The Python code for this looks like:
def binaryToDecimal(num):
decimal_number = 0
power = 0
for digit in reversed(num):
decimal_number += int(digit) * (2 ** power)
power += 1
return decimal_number