Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Display the binary, octal, and hex of a number - Python Program

To display the binary, octal, and hexadecimal representations of a number in Python, you can use built-in functions or string formatting.

Using built-in functions:

Python provides dedicated functions for this purpose:

  • bin(): Converts an integer to its binary representation (prefixed with 0b).
  • oct(): Converts an integer to its octal representation (prefixed with 0o).
  • hex(): Converts an integer to its hexadecimal representation (prefixed with 0x).

Type 1 Program

num = int(input("Enter a number: ")) print("Decimal:", num) print("Binary:", bin(num)) print("Octal:", oct(num)) print("Hexadecimal:", hex(num))

Output

 
OUTPUT  1:
Enter a number: 25
Decimal: 25
Binary: 0b11001
Octal: 0o31
Hexadecimal: 0x19

OUTPUT  2:

Enter a number: 255
Decimal: 255
Binary: 0b11111111
Octal: 0o377
Hexadecimal: 0xff

Using string formatting:

You can also use f-strings or the format() method with specific format specifiers: b: Binary format, o: Octal format, x: Hexadecimal format (lowercase), and X: Hexadecimal format (uppercase).

 

Example:

num = int(input("Enter a number: ")) print(f"Decimal: {num}") print(f"Binary: {num:b}") print(f"Octal: {num:o}") print(f"Hexadecimal (lowercase): {num:x}") print(f"Hexadecimal (uppercase): {num:X}")

Output

 
OUTPUT  1:
Enter a number: 255
Decimal: 255
Binary: 11111111
Octal: 377
Hexadecimal (lowercase): ff
Hexadecimal (uppercase): FF

OUTPUT  2:

Enter a number: 25
Decimal: 25
Binary: 11001
Octal: 31
Hexadecimal (lowercase): 19
Hexadecimal (uppercase): 19