Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Binary, octal, and hexadecimal are different number systems used in computing and digital electronics. Each of these number systems has a different base or radix and uses a different set of symbols to represent numbers.
Binary: The binary number system has a base of 2, which means it uses only two symbols, usually represented as 0 and 1. This number system is commonly used in computer science and digital electronics, where each bit (binary digit) can only have one of two values, 0 or 1. In binary, each digit represents a power of 2, starting from 2^0 (which is 1) and increasing by powers of 2. For example, the binary number 1010 represents:
1 x 2^3 + 0 x 2^2 + 1 x 2^1 + 0 x 2^0 = 8 + 0 + 2 + 0 = 10 (in decimal)
Octal: The octal number system has a base of 8, which means it uses eight symbols, usually represented as 0, 1, 2, 3, 4, 5, 6, and 7. Octal is sometimes used in computing, but it is not as common as binary or hexadecimal. In octal, each digit represents a power of 8, starting from 8^0 (which is 1) and increasing by powers of 8.
Hexadecimal: The hexadecimal number system has a base of 16, which means it uses 16 symbols, usually represented as 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. Hexadecimal is commonly used in computing and digital electronics, especially in programming and web development. In hexadecimal, each digit represents a power of 16, starting from 16^0 (which is 1) and increasing by powers of 16.
Hexadecimal is often used because it provides a compact representation of binary numbers. Each hexadecimal digit represents four binary digits (bits), so two hexadecimal digits can represent a byte (8 bits) of data. Additionally, hexadecimal numbers are easier for humans to read and remember than binary numbers, while still being easy to convert to binary or decimal when needed.
Python Code :
The below Python program converts decimal numbers to binary, octal, and hexadecimal:
# take input from user decimal = int(input("Enter a decimal number: ")) # convert decimal to binary, octal, and hexadecimal binary = bin(decimal) octal = oct(decimal) hexadecimal = hex(decimal) # print the results print(decimal, "in binary is", binary) print(decimal, "in octal is", octal) print(decimal, "in hexadecimal is", hexadecimal)
In this program, we first take input from the user for the decimal number to be converted. We then use the built-in functions bin(), oct(), and hex() to convert the decimal number to its binary, octal, and hexadecimal equivalents, respectively.
Finally, we print the original decimal number along with its binary, octal, and hexadecimal equivalents using the print() function. The output will be in the format of “number in base is equivalent value”.
For example :
Enter a decimal number: 200 200 in binary is 0b11001000 200 in octal is 0o310 200 in hexadecimal is 0xc8