Skip to main content

How to convert a number to a different base in Python

How to convert a number to a different base in Python.

Here's a step-by-step tutorial on how to convert a number to a different base in Python:

Step 1: Obtain the number you want to convert

  • Assign the number to a variable. For example, let's say we want to convert the decimal number 145 to binary.
number = 145

Step 2: Choose the base you want to convert to

  • Determine the base you want to convert the number to. For example, let's convert the decimal number to binary, so the base is 2.
base = 2

Step 3: Initialize an empty list to store the converted digits

  • Create an empty list to store the converted digits in the new base.
converted_digits = []

Step 4: Perform the conversion

  • Use a loop to repeatedly divide the number by the base until the number becomes zero.
  • At each iteration, append the remainder (digit) to the list of converted digits and update the number by dividing it by the base.
while number > 0:
remainder = number % base
converted_digits.append(remainder)
number = number // base

Step 5: Reverse the order of the converted digits

  • The digits are stored in reverse order because they were appended to the list from right to left. To obtain the correct order, reverse the list using the reverse() method.
converted_digits.reverse()

Step 6: Convert the list of digits to a string (optional)

  • If you want to represent the converted number as a string, use the join() method to concatenate the digits in the list into a single string.
converted_number = ''.join(str(digit) for digit in converted_digits)

Step 7: Print or use the converted number

  • You can print the converted number or use it for further calculations.
print(converted_number)

Putting it all together, here's an example that converts the decimal number 145 to binary:

number = 145
base = 2
converted_digits = []

while number > 0:
remainder = number % base
converted_digits.append(remainder)
number = number // base

converted_digits.reverse()
converted_number = ''.join(str(digit) for digit in converted_digits)
print(converted_number)

Output:

10010001

That's it! You have successfully converted a number to a different base in Python.