- Перевод чисел в Python
- Python: Int to Binary (Convert Integer to Binary String)
- What are Binary Strings for Integers?
- Use Python bin to Convert Int to Binary
- Use Python String Formatting to Convert Int to Binary
- Use Python f-strings to Convert Int to Binary
- Use Python format to Convert Int to Binary
- Convert an Int to Binary in Python without a Function
- Conclusion
Перевод чисел в Python
В данной статье мы рассмотрим встроенные функции языка программирования Python по переводу чисел в различные системы счисления. А так же напишем универсальную функцию по переводу десятичных чисел в другие системы счисления.
Перевод чисел из десятичной системы счисления
Для перевода числа из десятичной системы счисления в двоичную можно воспользоваться оператором bin(). В качестве аргумента нужно передать значение в виде числа, а оператор вернет строку с двоичным числом. У результата также будет префикс 0b, указывающий на основание системы счисления.
number = 123 result = bin(number) print(result)
Для перевода в восьмеричную систему счисления есть оператор oct(). Он также возвращает строку с восьмеричным числом и префиксом 0o.
number = 123 result = oct(number) print(result)
При переводе в шестнадцатеричную систему счисления воспользуемся оператором hex(). Он вернет строку шестнадцатеричным числом и префиксом 0x
number = 123 result = hex(number) print(result)
Если же вам не нужен префикс у результата перевода, то всегда можно взять срез у полученной строки.
print(bin(123)[2:]) print(oct(123)[2:]) print(hex(123)[2:])
Так же выводить числа в других системах счисления можно используя f-строки и формат вывода. Для этого в строке, через символ : указываем буквы b – для двоичной, o – для восьмеричной и x – для шестнадцатеричной системы счисления.
n = 1984 print(f'Двоичное: ') print(f'Восьмеричное: ') print(f'Шестнадцатеричное: ')
Двоичное: 11111000000 Восьмеричное: 3700 Шестнадцатеричное: 7c0
А теперь напишем универсальную функцию convert_to() по переводу чисел из десятичной системы счисления в систему счисления в любым основанием. Наша функция будет ограничена только наличием символов в переводимой системе счисления.
Данная функция принимает три аргумента, два из которых обязательные. Это десятичное целое число number и основание переводимой системы счисления base. Третий аргумент upper служит для указания регистра вывода строки переведенного числа. По умолчанию он установлен в значение False.
def convert_to(number, base, upper=False): digits = '0123456789abcdefghijklmnopqrstuvwxyz' if base > len(digits): return None result = '' while number > 0: result = digits[number % base] + result number //= base return result.upper() if upper else result
Во второй строке мы задаем переменную digits, содержащую набор символов цифр и букв английского языка. Она нам понадобится для составления символов переведенного числа на основании остатков.
В третьей строке мы проверяем основание переданной системы счисления на его длину. Если основание окажется больше, чем количество символов в нашей строке digits, то мы прекращаем выполнение функции через вызов оператора return и возвращаем None. Это такая своеобразная защита функции от неправильно переданных аргументов. Если мы попробуем перевести число в большую систему счисления по основанию, чем у нас есть символов для его записи, то мы его не сможем записать.
Дальше заведем переменную result для хранения результата работы функции и зададим ей значение в виде пустой строки. Теперь с помощью цикла с условием будем находить остаток от деления числа number на основание base, а также уменьшать number в base раз используя целочисленное деление.
Остаток от деления числа на основание переводимой системы счисления мы будем использовать как индекс для получения символа в строке digits и добавлять его к результату result. Добавлять это значение следует слева, т.к. самый первый остаток является самым правым разрядом. Цикл выполняется до тех пор, пока исходное значение переменной number больше нуля.
После завершения цикла мы вернем результат через вызов return. Для этого воспользуемся тернарным оператором и проверим наш третий аргумент. Если он будет в значении True, то для строки result вызовем строкой метод .upper() который заменит все прописные символы английского языка на строчные. Иначе, вернем результат как есть.
А теперь проверим работу нашей функции. Для этого попробуем перевести числа в 2ю, 8ю, 16ю, 32ю и 64ю системы счисления. Для перевода в 32ю систему счисления мы укажем третий необязательный аргумент upper и зададим ему значение True.
print(convert_to(123, 2)) print(convert_to(123, 8)) print(convert_to(123, 16)) print(convert_to(123, 32, upper=True)) print(convert_to(123, 64))
Перевод чисел в десятичную систему счисления
Для обратного перевода в десятичную систему счисления мы будем использовать оператор int(). Для этого передадим ему два аргумента, первый – это строка с числом в какой-то системе счисления, а второй – это основание системы счисления самого числа. По умолчанию для этого необязательного аргумента стоит значение равное 10.
В качестве самого числа нужно обязательно передать строку. Строка может содержать или само число или число с префиксом системы счисления.
Для перевода из двоичной системы счисления:
number = '11001' result = int(number, 2) print(result)
number = '0b11001' result = int(number, 2) print(result)
Для перевода из восьмеричной системы счисления:
Python: Int to Binary (Convert Integer to Binary String)
You’ll learn a brief overview of this conversion and how binary strings are represented in computers. Then, you’ll learn how to use four different methods to use Python to convert int to binary. These include, the bin() function, string formatting, f-strings, the format() function, as well as naive implementation without the use of any functions.
The Quick Answer: Use the format() Function
What are Binary Strings for Integers?
The common integer system that we’re used to, the decimal system, uses a base of ten, meaning that it has ten different symbols. These symbols are the numbers from 0 through to 9, which allow us to make all combinations of numbers that we’re familiar with.
Binary strings, on the other hand, use a base of two, meaning that they only have two numbers to express different numbers. These numbers are either 0 or 1. While the binary number system has been in use in different ancient civilizations (such as Egypt and India), it is used extensively in electronics and computer system in modern times.
In the next sections, you’ll learn how to use Python to convert an integer to a binary using the bin() function.
Want to learn how to get a file’s extension in Python? This tutorial will teach you how to use the os and pathlib libraries to do just that!
Use Python bin to Convert Int to Binary
The Python bin() function is short for binary and allows us to convert an integer to a binary string, which is prefixed by ‘0b’ . In later section, you’ll learn how to convert the integer using Python without the prefix.
Let’s take a look at how we can turn a positive integer into a binary string using Python:
# Convert an integer to a binary string using Python bin() positive = 123 binary = bin(positive) print(binary) Returns: '0b1111011'
We can see that a binary string with the ‘0b’ prefix has been returned.
Let’s check the type of the statement that’s been returned, using the built-in type() function:
# Checking the type of our binary string positive = 123 binary = bin(positive) print(type(binary)) # Returns: #
We can see here that the function returned a string, as expected.
Now let’s see what happens when we pass in a negative integer and try to use Python to convert it to binary string:
# Convert an integer to a binary string using Python bin() negative = -123 binary = bin(negative) print(binary) Returns: '-0b1111011'
We can see that there’s also a ‘-‘ prefix to our string, letting us know that the number is a negative value.
In the next section, you’ll learn how to use Python string formatting to convert an int to a binary string.
Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.
Use Python String Formatting to Convert Int to Binary
If you’re wanting to convert a Python integer to a binary string without the ‘0b’ prefix, you can use string formatting.
Python string formatting allows us to define different format types for passing in values. In this case, we’ll pass in the format code of » , which allows us to convert an integer to binary.
Let’s see how we can pass in a few integer values, both positive and negative, and convert them to binary string using string formatting:
# Convert an integer to a binary string using Python string formatting positive = 123 negative = -123 positive_binary = ''.format(positive) negative_binary = ''.format(negative) print(f'') print(f'') # Returns: # positive_binary='1111011' # negative_binary='-1111011'
We can see here that this method returns the same strings, without the ‘0b’ prefix.
In the next section, you’ll learn Python f-strings to convert an int to a binary string.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Use Python f-strings to Convert Int to Binary
Python f-strings allow us to make string formatting a little bit more intuitive. They also allow us to apply formatting to our strings in similar ways to traditional string formatting.
As a quick refresher on Python f-strings, they’re strings introduced in Python versions 3.6 and above, and are created by prefixing either a ‘f’ or ‘F’ to the string.
Let’s see how we can convert an integer to a binary string using Python f-strings. We’ll try this for the same positive and negative integers as above:
# Convert an integer to a binary string using Python f-strings positive = 123 negative = -123 positive_binary = f'' negative_binary = f'' print(f'') print(f'') # Returns: # positive_binary='1111011' # negative_binary='-1111011'
We can see here that the same values are returned. Python f-strings may not work in all versions of Python, but they are intuitive and easy to understand.
In the next section, you’ll learn how to use the Python format() function to convert an int to a binary string.
Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!
Use Python format to Convert Int to Binary
Another way to convert a Python integer to a binary string is to use the built-in format() function. The format() function takes value and a format spec as its arguments.
Because of this, we can pass in a value (in this case, an integer) and a format spec (in this case “b”), to specify that we want to return a binary string.
Let’s see how we can accomplish this using Python:
# Convert an integer to a binary string using Python format() positive = 123 negative = -123 positive_binary = format(positive, 'b') negative_binary = format(negative, 'b') print(positive_binary) print(negative_binary) # Returns: # positive_binary='1111011' # negative_binary='-1111011'
This is also a very readable way in which we can convert Python integers to string. The function makes it clear that we’re converting a value to something else, even specifying a type.
In the final section, you’ll learn how to convert an int to a binary string from scratch.
Want to learn how to calculate and use the natural logarithm in Python. Check out my tutorial here, which will teach you everything you need to know about how to calculate it in Python.
Convert an Int to Binary in Python without a Function
In this final section, you’ll learn how to convert how to create a naive method to convert a Python integer to a string. You’ll actually create a custom function that does this, but be able to understand how the conversion works.
Practically speaking, this is not something you’d really need to do, but it can be a helpful task to understand for programming interviews.
# Convert an integer to a binary string using a custom function def int_to_binary(integer): binary_string = '' while(integer > 0): digit = integer % 2 binary_string += str(digit) integer = integer // 2 binary_string = binary_string[::-1] return binary_string print(int_to_binary(123)) # Returns: # 1111011
Conclusion
In this post, you learned how to use Python to convert int to binary, meaning how to convert integer values to binary strings. You learned how to do this using a number of different methods, including using the Python bin() function, string formatting, f-strings, the format() function, and without any functions at all.
If you want to learn more about the Python bin() function, check out the official documentation here. To learn more about the Python format() function, you can find the official documentation here.