Convert binary, octal, decimal, and hexadecimal in Python | note.nkmk.me (2024)

In Python, you can handle numbers and strings in binary (bin), octal (oct), and hexadecimal (hex) formats, as well as in decimal. These formats can be converted among each other.

Contents

  • Represent integers in binary, octal, and hexadecimal formats
  • Convert a number to a binary, octal, and hexadecimal string
    • bin(), oct(), and hex()
    • format(), str.format(), and f-strings
    • Convert a negative integer to a string in two's complement representation
  • Convert a binary, octal, and hexadecimal string to a number
    • int()
  • Practical examples
    • Arithmetic with binary strings
    • Convert between binary, octal, and hexadecimal numbers

See the following article for the basics of conversion between the string (str) and the number (int, float).

  • Convert a string to a number (int, float) in Python

Represent integers in binary, octal, and hexadecimal formats

Integers (int) can be expressed in binary, octal, and hexadecimal formats by appending the prefixes 0b, 0o, and 0x. However, the print() function will present the output in decimal notation.

bin_num = 0b10oct_num = 0o10hex_num = 0x10print(bin_num)print(oct_num)print(hex_num)# 2# 8# 16

The prefixes can also be denoted in uppercase forms as 0B, 0O, and 0X.

Bin_num = 0B10Oct_num = 0O10Hex_num = 0X10print(Bin_num)print(Oct_num)print(Hex_num)# 2# 8# 16

Despite the prefix, the data type remains int.

print(type(bin_num))print(type(oct_num))print(type(hex_num))# <class 'int'># <class 'int'># <class 'int'>print(type(Bin_num))print(type(Oct_num))print(type(Hex_num))# <class 'int'># <class 'int'># <class 'int'>

These numbers can be subjected to standard arithmetic operations.

result = 0b10 * 0o10 + 0x10print(result)# 32

In Python3.6 and later, you can insert underscores _ within numbers for better readability. Inserting consecutive underscores raises an error, but you can include as many non-consecutive underscores as you like.

The underscore can be used as a delimiter for better readability in large numbers. For example, inserting an underscore every four digits can make the number more readable.

print(0b111111111111 == 0b1_1_1_1_1_1_1_1_1_1_1_1)# Truebin_num = 0b1111_1111_1111print(bin_num)# 4095

Convert a number to a binary, octal, and hexadecimal string

You can convert a number to a binary, octal, or hexadecimal string using the following functions:

  • Built-in function bin(), oct(), hex()
  • Built-in function format(), string method str.format(), f-strings

The article also explains how to obtain a string in two's complement representation for a negative value.

bin(), oct(), and hex()

The built-in functions bin(), oct(), and hex() convert numbers into binary, octal, and hexadecimal strings. Each function returns a string prefixed with 0b, 0o, and 0x.

i = 255print(bin(i))print(oct(i))print(hex(i))# 0b11111111# 0o377# 0xffprint(type(bin(i)))print(type(oct(i)))print(type(hex(i)))# <class 'str'># <class 'str'># <class 'str'>

If the prefix is not required, you can use slice notation [2:] to extract the remainder of the string, or you can employ the format() function as described next.

  • How to slice a list, string, tuple in Python
print(bin(i)[2:])print(oct(i)[2:])print(hex(i)[2:])# 11111111# 377# ff

To convert into a decimal string, simply use str().

print(str(i))# 255print(type(str(i)))# <class 'str'>

format(), str.format(), and f-strings

The built-in function format(), the string method str.format(), and f-strings can also be used to convert a number to a binary, octal, and hexadecimal string.

You can convert a number to a binary, octal, or hexadecimal string by specifying b, o, or x in the format specification string, which is used as the second argument of format().

i = 255print(format(i, 'b'))print(format(i, 'o'))print(format(i, 'x'))# 11111111# 377# ffprint(type(format(i, 'b')))print(type(format(i, 'o')))print(type(format(i, 'x')))# <class 'str'># <class 'str'># <class 'str'>

To append the prefix 0b, 0o, and 0x to the output string, include # in the format specification string.

print(format(i, '#b'))print(format(i, '#o'))print(format(i, '#x'))# 0b11111111# 0o377# 0xff

It is also possible to pad the number with zeros to a certain length. However, when padding a number with a prefix, remember to include the two characters of the prefix in your count.

print(format(i, '08b'))print(format(i, '08o'))print(format(i, '08x'))# 11111111# 00000377# 000000ffprint(format(i, '#010b'))print(format(i, '#010o'))print(format(i, '#010x'))# 0b11111111# 0o00000377# 0x000000ff

The string method str.format() can also perform the same conversion.

print('{:08b}'.format(i))print('{:08o}'.format(i))print('{:08x}'.format(i))# 11111111# 00000377# 000000ff

For details about format() and str.format(), including format specification strings, see the following article.

  • Format strings and numbers with format() in Python

In Python 3.6 or later, you can also use f-strings to write more concisely.

  • How to use f-strings in Python
print(f'{i:08b}')print(f'{i:08o}')print(f'{i:08x}')# 11111111# 00000377# 000000ff

Convert a negative integer to a string in two's complement representation

The bin() or format() functions convert negative integers into their absolute values, prefixed with a minus sign.

x = -9print(x)print(bin(x))# -9# -0b1001

Python performs bitwise operations on negative integers in two's complement representation. So, if you want the binary string in two's complement form, use the bitwise-and operator (&) with the maximum number required for your digit size. For example, use 0b1111 (= 0xf) for 4-bit, 0xff for 8-bit, and 0xffff for 16-bit representations.

print(bin(x & 0xff))print(format(x & 0xffff, 'x'))# 0b11110111# fff7

Convert a binary, octal, and hexadecimal string to a number

int()

You can use the built-in function int() to convert a binary, octal, or hexadecimal string into a number.

The int() function accepts a string and a base as arguments to convert the string into an integer. The base signifies the number system to be used. If the base is omitted, the function assumes the string is in decimal.

print(int('10'))print(int('10', 2))print(int('10', 8))print(int('10', 16))# 10# 2# 8# 16print(type(int('10')))print(type(int('10', 2)))print(type(int('10', 8)))print(type(int('10', 16)))# <class 'int'># <class 'int'># <class 'int'># <class 'int'>

If the radix is set to 0, the function determines the base according to the prefix (0b, 0o, 0x or 0B, 0O, 0X).

print(int('0b10', 0))print(int('0o10', 0))print(int('0x10', 0))# 2# 8# 16print(int('0B10', 0))print(int('0O10', 0))print(int('0X10', 0))# 2# 8# 16

With the radix set to 0, a string without a prefix is interpreted as a decimal number. Note that leading zeros in the string will cause an error.

print(int('10', 0))# 10# print(int('010', 0))# ValueError: invalid literal for int() with base 0: '010'

In other cases, a string padded with 0 can be successfully converted.

print(int('010'))# 10print(int('00ff', 16))print(int('0x00ff', 0))# 255# 255

The function raises an error if the string cannot be converted according to the specified radix or prefix.

# print(int('ff', 2))# ValueError: invalid literal for int() with base 2: 'ff'# print(int('0a10', 0))# ValueError: invalid literal for int() with base 0: '0a10'# print(int('0bff', 0))# ValueError: invalid literal for int() with base 0: '0bff'

Practical examples

Arithmetic with binary strings

For example, to perform operations on binary strings prefixed with 0b, convert them into an integer int, conduct the desired operation, and then transform them back into a string str.

a = '0b1001'b = '0b0011'c = int(a, 0) + int(b, 0)print(c)print(bin(c))# 12# 0b1100

Convert between binary, octal, and hexadecimal numbers

It is straightforward to convert binary, octal, and hexadecimal strings to one another by converting them first to the int format and then into any desired format.

You can control the addition of zero-padding and prefixes using the formatting specification string.

a_0b = '0b1110001010011'print(format(int(a, 0), '#010x'))# 0x00000009print(format(int(a, 0), '#010o'))# 0o00000011
Convert binary, octal, decimal, and hexadecimal in Python | note.nkmk.me (2024)

FAQs

How to convert binary to decimal, octal, and hexadecimal in Python? ›

In the above program, we have used the inbuilt functions: bin() (for binary), oct() (for octal), and hex() (for hexadecimal) for converting the given decimal number into respective number systems. These functions take an integer and return a string.

How to convert between binary octal decimal and hexadecimal? ›

Binary to hexadecimal: Take groups of 4 bits, from right to left, and convert to hexadecimal digits directly. Octal to decimal: Take each digit from right to left, multiply it by the place value, and add to the running total. Octal to binary: Expand each octal digit into the 3 bits it represents (from left to right).

How to convert octal to hexadecimal in Python? ›

The simplest way is to convert the octal number into a decimal, then the decimal into hexadecimal form.
  1. Write the powers of 8 (1, 8, 64, 512, 4096, and so on) beside the octal digits from bottom to top.
  2. Multiply each digit by its power.
  3. Add up the answers. ...
  4. Divide the decimal number by 16.
Sep 19, 2023

How to convert from binary to hexadecimal in Python? ›

First convert the given binary number into decimal and print the hexadecimal number.
  1. n = int(input('Enter binary number: '),2)
  2. print('Hexadecimal number: ',hex(n)[2:])
Mar 28, 2019

What is hex() in Python? ›

Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer.

How do you convert binary to decimal and hexadecimal? ›

The binary number can be converted to a decimal number by expressing each digit as a product of the given number 1 or 0 to the respective power of 2. And to convert from decimal to hexadecimal we divide the number 16 until the quotient is zero.

What are the steps to convert octal to hexadecimal? ›

It is common practice to convert from octal to hexadecimal by first turning the octal number into a binary digit, and then from binary to hexadecimal. To get its hexadecimal equivalent, we now group the four binary bits together. 536 is represented by the hexadecimal value 15E.

Is it possible to convert between octal and hexadecimal number systems? ›

The conversion of these numbers from one form to another is possible. To convert hexadecimal to octal numbers, we need to convert hexadecimal to its equivalent decimal number first and then decimal to octal. Before this conversion, first, go through the basic definition of hexadecimal and octal numbers.

How to convert decimal into hexadecimal in Python? ›

Using the hex() function

We can convert a decimal number to hexadecimal in Python using the built-in hex() function. It takes a parameter decimal number and returns its hexadecimal number.

How do you convert to octal in Python? ›

In Python, you can use the oct() function to convert from a decimal value to its corresponding octal value. Alternatively, you can also use the int() function and the correct base, which is 8 for the octal number system.

How to turn binary to decimal in Python? ›

One more approach using the built-in int() function with a bit-wise shift operator:
  1. binary = input("Enter a binary number: ")
  2. decimal = 0.
  3. for digit in binary:
  4. decimal = (decimal << 1) | int(digit)
  5. print("Decimal equivalent of", binary, "is", decimal)

How to convert from decimal to binary, octal, and hexadecimal? ›

In decimal to binary, we divide the number by 2, in decimal to hexadecimal we divide the number by 16. In case of decimal to octal, we divide the number by 8 and write the remainders in the reverse order to get the equivalent octal number. Decimal Number: All the numbers to the base ten are called decimal numbers.

How to convert binary data to ASCII in Python? ›

Below are the steps:
  1. Declare a function that takes the binary value as an argument.
  2. Then, use the chr() method to convert each of the bits passed into its ASCII value by passing the chr() method an integer value whose base is 2 i.e., in binary.
Feb 8, 2024

How do you convert binary to decimal and decimal to octal? ›

In decimal to binary, we divide the number by 2, in decimal to hexadecimal we divide the number by 16. In case of decimal to octal, we divide the number by 8 and write the remainders in the reverse order to get the equivalent octal number. Decimal Number: All the numbers to the base ten are called decimal numbers.

What is 08b in Python? ›

The '08b' part tells Python to show 8 binary numbers, including leading zeroes. This makes it easier to look at binary numbers when you want to compare them.

How to convert decimal to octal number in Python? ›

We can convert decimal to octal by following these steps:
  1. After dividing the number by 8, we store the remainder in an array.
  2. Divide the number by 8 now.
  3. Repeat the above two steps until the number becomes equal to zero.
  4. Now, print the array in reverse order.

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Edmund Hettinger DC

Last Updated:

Views: 5341

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.