Python convert int to any base

vikas-0 / base10toN.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

def base10toN ( num , n ):
«»»Change a to a base-n number.
Up to base-36 is supported without special notation.»»»
num_rep = < 10 : 'a' ,
11 : ‘b’ ,
12 : ‘c’ ,
13 : ‘d’ ,
14 : ‘e’ ,
15 : ‘f’ ,
16 : ‘g’ ,
17 : ‘h’ ,
18 : ‘i’ ,
19 : ‘j’ ,
20 : ‘k’ ,
21 : ‘l’ ,
22 : ‘m’ ,
23 : ‘n’ ,
24 : ‘o’ ,
25 : ‘p’ ,
26 : ‘q’ ,
27 : ‘r’ ,
28 : ‘s’ ,
29 : ‘t’ ,
30 : ‘u’ ,
31 : ‘v’ ,
32 : ‘w’ ,
33 : ‘x’ ,
34 : ‘y’ ,
35 : ‘z’ >
new_num_string = »
current = num
while current != 0 :
remainder = current % n
if 36 > remainder > 9 :
remainder_string = num_rep [ remainder ]
elif remainder >= 36 :
remainder_string = ‘(‘ + str ( remainder ) + ‘)’
else :
remainder_string = str ( remainder )
new_num_string = remainder_string + new_num_string
current = current // n
return new_num_string

Источник

Inter-Convert Decimal and Any Base Using Python

This post deals with the methods to inter-convert decimal to any base system number into any base depending on the user input in Python.

Prerequisites: Basics of python looping constructs

Decimal to Any Base – The Method

The basic algorithm for this conversion is to repeatedly divide (integer division) the given decimal number by the target base value until the decimal number becomes 0. The remainder in each case forms the digits of the number in the new base system, however, in the reverse order.

Читайте также:  Php rabbitmq queue declare

An Upper Limit

The algorithm, in general, will work for any base, but we need digits/characters to represent that many numbers of a base system. For simplicity, we limit ourselves to base 36 i.e 10 numbers + 26 alphabets. (We can differentiate lower and upper case, but we intend to focus on the algorithm here!). It will be clear after the implementation that the method has to work for any base.

Decimal to Any Base – Python Implementation

Consider the following program,

def dec_to_base(num,base): #Maximum base - 36 base_num = "" while num>0: dig = int(num%base) if dig

Notice the if condition used to check if digits 0-9 are enough to accommodate all digits in the base. Otherwise, we are assigning a suitable alphabet for the digit.

ord() – Built-in function that returns the ASCII value of character

chr() – Built-in function that returns the character with ASCII value –

The last line is used as a string reversal operation. It basically produces a slice of string from beginning to end ( signified by first two empty arguments) by traversing from the end to start (signified by -1).

This a sample output, converting to base 28

Inter-Convert Decimal and Any Base Using Python

Hence we are able to convert a decimal number into any base required.

Some Built-In Base Conversion Methods

Python provides some built-in base conversion methods for binary, octal and hexadecimal numbers.

bin() – Returns a string, which is binary representation of decimal number

oct() – Returns a string, which is octal representation of decimal number

hex() – Returns a string, which is hecadecimal representation of decimal number

Any Base to Decimal

Python also provides easy conversion from any base to decimal. This done by simply passing a string that has the other base representation of a decimal number and the base value as the second argument. It returns the decimal number!

print int("1123",5) #Prints string given in base-5 in decimal

Algorithm and Implementation for Any Base to Decimal

The logic is very simple. We just have to multiply each digit at a position with the base value raised to the place value(starting from 0 from right-side). That is how a base system is defined, in fact.

For instance, if 1011 is a binary number, the decimal equivalent is

(1 x 2^0) + (1 x 2^1) + (0 x 2^2) + (1 x 2^3) = 11

The following program illustrates the same,

def base_to_dec(num_str,base): num_str = num_str[::-1] num = 0 for k in range(len(num_str)): dig = num_str[k] if dig.isdigit(): dig = int(dig) else: #Assuming its either number or alphabet only dig = ord(dig.upper())-ord('A')+10 num += dig*(base**k) return num

Below is a sample output for the same value converted in the previous output

converted output value in Python

Feel free to leave behind any sort of feedback, suggestion, doubts below.

Источник

Base conversion functions in Python

Python provides base conversion functions to convert an integer number to another base. Whenever you print a binary, octal or a hexadecimal integer number, it is printed by default in decimal form. But sometimes there is a need to change base of an integer, for example, decimal form to binary form.

Please note that all binary, octal and hexadecimal representation can not be used for fractional numbers, for example, 1.33.

Following are the base conversion functions:

bin() Convert an integer number to a binary string prefixed with “0b”
oct() Convert an integer number to an octal string prefixed with “0o”
hex() Convert an integer number to a lowercase hexadecimal string prefixed with “0x”

In the following program we’ll convert decimal, binary, octal and hexadecimal integer numbers in other base.

decimalNumber = 123 binaryNumber = 0b101 hexNumber = 0x111 octNumber = 0o111 #convert decimal number to other base print('Binary representation of decimalNumber is ', bin(decimalNumber)) print('Hexadecimal representation of decimalNumber is ', hex(decimalNumber)) print('Octal representation of decimalNumber is ', oct(decimalNumber)) #to print empty line in console print() #convert binary number to other base print('Decimal representation of binaryNumber is ', int(binaryNumber)) print('Hexadecimal representation of binaryNumber is ', hex(binaryNumber)) print('Octal representation of binaryNumber is ', oct(binaryNumber)) #to print empty line in console print() #convert hexadecimal number to other base print('Decimal representation of hexNumber is ', int(hexNumber)) print('Hexadecimal representation of hexNumber is ', bin(hexNumber)) print('Octal representation of hexNumber is ', oct(hexNumber)) #to print empty line in console print() #convert octal number to other base print('Decimal representation of octNumber is ', int(octNumber)) print('Binary representation of octNumber is ', bin(octNumber)) print('Hexadecimal representation of octNumber is ', hex(octNumber))
Binary representation of decimalNumber is 0b1111011 Hexadecimal representation of decimalNumber is 0x7b Octal representation of decimalNumber is 0o173 Decimal representation of binaryNumber is 5 Hexadecimal representation of binaryNumber is 0x5 Octal representation of binaryNumber is 0o5 Decimal representation of hexNumber is 273 Hexadecimal representation of hexNumber is 0b100010001 Octal representation of hexNumber is 0o421 Decimal representation of octNumber is 73 Binary representation of octNumber is 0b1001001 Hexadecimal representation of octNumber is 0x49

Источник

Перевод чисел в 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() который заменит все прописные символы английского языка на строчные. Иначе, вернем результат как есть.

А теперь проверим работу нашей функции. Для этого попробуем перевести числа в , , 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)

Для перевода из восьмеричной системы счисления:

Источник

Оцените статью