note.nkmk.me

Convert binary, octal, decimal, and hexadecimal in Python

Posted: 2021-01-05 / Modified: 2021-01-07 / Tags: Python, String

In Python, you can handle numbers and strings as binary (bin), octal (oct) and hexadecimal (hex) as well as decimal. They can also be converted to each other.

This article describes the following contents.

  • Write integers in binary, octal and hexadecimal notation
  • Convert a numbers to a binary, octal and hexadecimal string
    • bin(), oct(), hex()
    • format(), str.format(), 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()
  • Usage examples
    • Binary string arithmetic
    • 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).

Sponsored Link

Write integers in binary, octal and hexadecimal notation

By adding the prefixes 0b, 0o, and 0x, integer type int numbers can be written in binary, octal, and hexadecimal, respectively. 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

You can also use uppercase 0B, 0O, and 0X.

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

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

Even with a 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 they are int, they can be operated as usual.

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

In Python3.6 and later, you can insert underscores _ in numbers. Repeating the underscore _ raises an error, but if it is not repeated, you can insert as many as you like.

The underscore _ can be used as a delimiter when there are many digits. For example, it is easier to read if you enter _ every 4 digits.

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 a number to a binary, octal and hexadecimal string

To convert a number to a binary, octal or hexadecimal string, use the following functions.

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

It also describes how to get a string in two's complement representation for a negative value.

bin(), oct(), hex()

The built-in functions bin(), oct() and hex() can be used to convert a number to a binary, octal and hexadecimal string. These functions return a string with the prefixes 0b,0o and 0x, respectively.

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 trailing strings or use format() as described next.

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

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

print(str(i))
# 255

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

format(), str.format(), 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.

By specifying b, o and x in the format specification string of the second argument of format(), a number can be converted to a binary, octal and hexadecimal string, respectively.

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 the character string with the prefix 0b, 0o, 0x, add # to the format specification string.

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

It is also possible to fill in zero (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 the same conversion.

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

In Python3.6 or later, you can also use the f-strings (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 representation

When using bin() or format(), negative integers are converted to absolute values with a minus sign.

x = -9

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

In Python, bitwise operations on negative integers are performed in two's complement representation, so if you want to get a string expressed in two's complement representation, take the bitwise-and & of the maximum number of digits required, for example, 0b1111 (= 0xf) for 4bit, 0xff for 8bit, and 0xffff for 16bit.

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

Convert a binary, octal and hexadecimal string to a number

int()

Use the built-in function int() to convert a binary, octal and hexadecimal string into a number.

You can convert a binary, octal and hexadecimal string to an integer based on the radix with int(string, radix). If radix is omitted, it is assumed to be a decimal number.

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 you set radix to 0, it will be converted 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
# 16

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

When the radix is 0, a string without a prefix is converted as a decimal number. In that case, note that an error will occur if the beginning (left side) is padded with 0.

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

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

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

print(int('010'))
# 10

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

An error will occur if the string cannot be converted based on 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'

Usage examples

Binary string arithmetic

For example, if you want to perform an operation on a binary string with the prefix 0b, you can easily convert it to a integer int, perform the operation, and then convert it back to the 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 also easy to convert binary, octal, and hexadecimal strings to each other. Once converted to a number int, it can be converted to a string of any format.

Zero-padding and prefixes 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
Sponsored Link
Share

Related Categories

Related Articles