YouTip LogoYouTip

Python3 Conversion Binary Octal Hexadecimal

# Python3.x Python Decimal to Binary, Octal, Hexadecimal [![Image 3: Document Object Reference Manual](#) Python3 Examples](#) The following code is used to convert decimal to binary, octal, and hexadecimal: ## Example (Python 3.0+) # -*- coding: UTF-8 -*-# Filename : test.py# author by : www..com# Get user input decimal number dec = int(input("Enter a number: "))print("The decimal number is:", dec)print("Converted to binary:", bin(dec))print("Converted to octal:", oct(dec))print("Converted to hexadecimal:", hex(dec)) Executing the above code produces the following output: python3 test.py Enter a number: 5The decimal number is: 5Converted to binary: 0b101Converted to octal: 0o5Converted to hexadecimal: 0x5 The following examples demonstrate how to convert between different number systems. You can modify the input base and output format as needed. ### Binary Conversion Example ## Example binary_number ='101010' decimal_number =int(binary_number,2)# Convert binary to decimal octal_number =oct(decimal_number)# Convert decimal to octal hexadecimal_number =hex(decimal_number)# Convert decimal to hexadecimal print('Binary number:', binary_number) print('Converted to decimal:', decimal_number) print('Converted to octal:', octal_number) print('Converted to hexadecimal:', hexadecimal_number) Output: Binary number: 101010Converted to decimal: 42Converted to octal: 0o52Converted to hexadecimal: 0x2a ### Octal Conversion Example ## Example octal_number ='52' decimal_number =int(octal_number,8)# Convert octal to decimal binary_number = bin(decimal_number)# Convert decimal to binary hexadecimal_number =hex(decimal_number)# Convert decimal to hexadecimal print('Octal number:', octal_number) print('Converted to decimal:', decimal_number) print('Converted to binary:', binary_number) print('Converted to hexadecimal:', hexadecimal_number) Output: Octal number: 52Converted to decimal: 42Converted to binary: 0b101010Converted to hexadecimal: 0x2a ### Hexadecimal Conversion Example ## Example hexadecimal_number ='2a' decimal_number =int(hexadecimal_number,16)# Convert hexadecimal to decimal binary_number = bin(decimal_number)# Convert decimal to binary octal_number =oct(decimal_number)# Convert decimal to octal print('Hexadecimal number:', hexadecimal_number) print('Converted to decimal:', decimal_number) print('Converted to binary:', binary_number) print('Converted to octal:', octal_number) Output: Hexadecimal number: 2aConverted to decimal: 42Converted to binary: 0b101010Converted to octal: 0o52 [![Image 4: Document Object Reference Manual](#) Python3 Examples](#)
← Python3 Get YesterdayPython3 Upper Lower β†’