Python has built-in tools for number bases: format() writes a number in base 2, 8 or 16, and int(text, base) reads it back.
The program
n = int(input("Decimal number: ")) print("Binary: ", format(n, "b")) print("Octal: ", format(n, "o")) print("Hexadecimal:", format(n, "X")) text = input("Binary number: ") print("Decimal: ", int(text, 2))
Typed in this example: 42, 11111111. Press Run to type your own.
Decimal number: 42 Binary: 101010 Octal: 52 Hexadecimal: 2A Binary number: 11111111 Decimal: 255
How it works
format(n, "b")writesnin binary,"o"in octal, and"X"in hexadecimal with capital letters ("x"gives small letters). The same codes work in f-strings:f"{n:b}".bin(n),oct(n)andhex(n)do the same, but add a prefix:bin(42)is'0b101010'.int(text, 2)reads the text as a base-2 number.int("ff", 16)gives 255. If the text has a digit that is not allowed in that base, such as"102"in base 2, you get aValueError.
By hand
To convert to binary, divide by 2 again and again. The remainders, read from last to first, are the binary digits. To convert back, start at 0 and, for each digit, double the total and add the digit:
def to_binary(n): if n == 0: return "0" sign = "-" if n < 0 else "" n = abs(n) digits = "" while n > 0: digits = str(n % 2) + digits n //= 2 return sign + digits def from_binary(text): total = 0 for digit in text: total = total * 2 + int(digit) return total for n in [0, 5, 42, 255, -6]: print(n, to_binary(n)) print(from_binary("101010"))
0 0 5 101 42 101010 255 11111111 -6 -110 42
from_binary() here only handles positive numbers without a sign. The built-in int(text, 2) also accepts a sign and the 0b prefix: int("-110", 2) and int("0b110", 2) both work.