Convert binary, octal, and hexadecimal numbers and strings to and from each other in Python

Money and Business

Python can handle numbers and strings as binary, octal, and hexadecimal numbers as well as the usual decimal numbers. It is also easy to convert between them.

In this section, the following contents will be explained along with sample code.

  • Write integers in binary, octal, and hexadecimal.
  • Convert numbers to strings in binary, octal, and hexadecimal notation.
    • built-in function (e.g. in programming language)bin(),oct(),hex()
    • string methodstr.format(), Built-in Functionsformat(), f string
    • Convert a negative integer to a string in two's complement format.
  • Convert strings in binary, octal, and hexadecimal notation to numbers.
    • built-in function (e.g. in programming language)int()
  • Application Examples
    • Binary string arithmetic
    • Convert between binary, octal, and hexadecimal numbers

Write integers in binary, octal, and hexadecimal.

By adding the following prefixes, integer int numbers can be written in binary, octal, and hexadecimal, respectively.
You can also use capital letters.

  • Binary number:0bor0B
  • Octal:0oor0O
  • Hexadecimal number:0xor0X

The output of print() will be in decimal notation.

bin_num = 0b10
oct_num = 0o10
hex_num = 0x10

print(bin_num)
print(oct_num)
print(hex_num)
# 2
# 8
# 16

Bin_num = 0B10
Oct_num = 0O10
Hex_num = 0X10

print(Bin_num)
print(Oct_num)
print(Hex_num)
# 2
# 8
# 16

Even with the prefix, the type is an integer 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'>

Since it is an integer type, it can be used for regular arithmetic operations.

result = 0b10 * 0o10 + 0x10
print(result)
# 32

Starting with Python 3.6, it is possible to insert underscores _ in numbers. Repeating an underscore _ will result in an error, but you can insert as many as you like as long as you don't repeat it.

The _ underscore does not affect the number, so it can be used as a separator when there are many digits. For example, inserting an underscore _ every four digits is easy to read.

print(0b111111111111 == 0b1_1_1_1_1_1_1_1_1_1_1_1)
# True

bin_num = 0b1111_1111_1111
print(bin_num)
# 4095

Convert numbers to strings in binary, octal, and hexadecimal notation.

To convert a number into a string in binary, octal, or hexadecimal notation, use the following built-in functions.

  • built-in function (e.g. in programming language)bin(),oct(),hex()
  • string methodstr.format(), Built-in Functionsformat(), f string

This section also explains how to get a string expressed in two's complement format for negative values.

Built-in functions bin(), oct(), hex()

The following built-in functions can convert numbers into binary, octal, and hexadecimal strings.

  • Binary number:bin()
  • Octal:oct()
  • Hexadecimal number:hex()

Each returns a string with the following prefixes

  • Binary number:0b
  • Octal:0o
  • Hexadecimal number:0x
i = 255

print(bin(i))
print(oct(i))
print(hex(i))
# 0b11111111
# 0o377
# 0xff

print(type(bin(i)))
print(type(oct(i)))
print(type(hex(i)))
# <class 'str'>
# <class 'str'>
# <class 'str'>

If you don't need the prefix, use slice[2:] to extract the string behind it, or use format() as explained next.

print(bin(i)[2:])
print(oct(i)[2:])
print(hex(i)[2:])
# 11111111
# 377
# ff

If you want to convert it to a decimal string, you can use str().

print(str(i))
# 255

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

Built-in function format(), string method str.format(), f string

The built-in function format() and the string methods str.format() and f-string can also convert numbers to binary, octal, and hexadecimal strings.

By specifying the second argument of format() as follows, it can be converted to binary, octal, and hexadecimal strings, respectively.

  • Binary number:b
  • Octal:o
  • Hexadecimal number:x
print(format(i, 'b'))
print(format(i, 'o'))
print(format(i, 'x'))
# 11111111
# 377
# ff

print(type(format(i, 'b')))
print(type(format(i, 'o')))
print(type(format(i, 'x')))
# <class 'str'>
# <class 'str'>
# <class 'str'>

If you want to get a string with prefix 0b,0o,0x, add # to the formatting specification string.

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

It is also possible to fill in 0 with any number of digits. Note that the number of characters for the prefix (two characters) must also be taken into account when filling in zero with a prefix.

print(format(i, '08b'))
print(format(i, '08o'))
print(format(i, '08x'))
# 11111111
# 00000377
# 000000ff

print(format(i, '#010b'))
print(format(i, '#010o'))
print(format(i, '#010x'))
# 0b11111111
# 0o00000377
# 0x000000ff

The string method str.format() can be used for conversion as well.

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

Starting with Python 3.6, you can also use the f string.f'xxx'

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 format.

When a negative integer is converted to a binary or hexadecimal string using bin() or format(), the absolute value will have a minus sign.

x = -9

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

In Python, bitwise operations on negative integers are also performed in two's complement representation. Therefore, if you want to get a string expressed in two's complement form, you can take a bitwise logical OR& with the maximum number of bit digits required, as follows.

  • 4bit:0b1111(=0xf)
  • 8bit:0xff
  • 16bit:0xffff
print(bin(x & 0xff))
print(format(x & 0xffff, 'x'))
# 0b11110111
# fff7

Convert strings in binary, octal, and hexadecimal notation to numbers.

Built-in function int()

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

With int(string, radix), a string str in binary, octal, hexadecimal notation, etc. can be converted to a numeric int based on the radix. If the radix is omitted, the number is considered to be decimal.

print(int('10'))
print(int('10', 2))
print(int('10', 8))
print(int('10', 16))
# 10
# 2
# 8
# 16

print(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 conversion is done based on the following string prefix.

  • Binary prefix:0bor0B
  • Octal prefix:0oor0O
  • Hexadecimal prefix:0xor0X
print(int('0b10', 0))
print(int('0o10', 0))
print(int('0x10', 0))
# 2
# 8
# 16

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

If the base number is 0 and there is no prefix, it will be converted as a decimal number, but note that if the beginning (left side) is filled with 0, an error will occur.

print(int('10', 0))
# 10

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

In other cases, zero-filled strings can be converted as is.

print(int('010'))
# 10

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

If the string cannot be converted with the specified radix or prefix, an error occurs.

# 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'

Application Examples

Binary string arithmetic

For example, to perform an operation on a string in binary notation with the prefix 0b.

You can easily convert it to a numeric value (integer type int), perform operations on it, and then convert it back to a string str again.

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 also easy to convert binary, octal, and hexadecimal strings to each other. Once converted to a numeric int, it can be converted to a string of any format.

Zero-filling, prefixing, etc. can be controlled by the formatting specification string.

a_0b = '0b1110001010011'

print(format(int(a, 0), '#010x'))
# 0x00000009

print(format(int(a, 0), '#010o'))
# 0o00000011
Copied title and URL