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)
Top Articles
Latest Posts
Recommended Articles
Article information

Author: Van Hayes

Last Updated:

Views: 5954

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Van Hayes

Birthday: 1994-06-07

Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

Phone: +512425013758

Job: National Farming Director

Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.