Quickly convert Decimal to other bases in Python


To quickly convert Decimal to other based, we will be using the Built-in functions in Python −

  • Decimal to Binary − bin()
  • Decimal to Octal − oct()
  • Decimal to Hexadecimal − hex()

Decimal number system has base 10 as it uses 10 digits from 0 to 9. In decimal number system, the successive positions to the left of the decimal point represent units, tens, hundreds, thousands, and so on.

Binary uses two digits, 0 and 1. Also called as base 2 number system Each position in a binary number represents a 0 power of the base (2). Last position in a binary number represents a x power of the base (2).

Octal Number uses eight digits, 0,1,2,3,4,5,6,7. Also called as base 8 number system. Each position in an octal number represents a 0 power of the base (8). Last position in an octal number represents a x power of the base (8).

Hexadecimal Number System uses 10 digits and 6 letters, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F Letters represent the numbers starting from 10. A = 10. B = 11, C = 12, D = 13, E = 14, F = 15 Also called as base 16 number system.

Convert Decimal to Binary

To convert Decimal to Binary, use the bin() method and set the Decimal Number as a parameter −

Example

# Decimal Number dec = 110 # Display the Decimal Number print("Decimal = ",dec) # Display the Binary form print('The number {} in binary form = {}'.format(dec, bin(dec)))

Output

Decimal =  110
The number 110 in binary form = 0b1101110

Convert Decimal to Octal

To convert Decimal to Octal, use the oct() method and set the Decimal Number as a parameter −

Example

# Decimal Number dec = 110 # Display the Decimal Number print("Decimal = ",dec) # Display the Octal form print('The number {} in octal form = {}'.format(dec, oct(dec)))

Output

Decimal =  110
The number 110 in octal form = 0o156

Convert Decimal to Hexadecimal

To convert Decimal to Hexadecimal, use the hex() method and set the Decimal Number as a parameter −

Example

# Decimal Number dec = 110 # Display the Decimal Number print("Decimal = ",dec) # Display the Hexadecimal form print('The number {} in hexadecimal form = {}'.format(dec, hex(dec)))

Output

Decimal =  110
The number 110 in hexadecimal form = 0x6e

Updated on: 11-Aug-2022

949 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements