Convert numbers between numerical systems#

Learning to convert numbers between numerical systems is a fundamental skill in every programming language. Python provides built-in functions to convert numbers between binary, octal, decimal, and hexadecimal systems. While it seems like a simple task, it is essential to understand how to convert numbers between different numerical systems and how Python handles them.

Introduction to integer numbers#

Python supports integer numbers, which are whole numbers without a fractional part. Integer numbers can be positive or negative. The integer type in Python is called int. The int type can represent numbers in different numerical systems, such as binary, octal, decimal, and hexadecimal.

In the example below we assign a value to a variable and print it. We also use the type function to check the type of the value. As shown in the example, the value is an integer, and the type of the value is int.

Assign a value to a variable and print it#
>>> value = 128
>>> print(value)
128
>>> type(value)
<class 'int'>

Assign a value in a different numerical system#

Python also allows us to assign a value in a different numerical system. We can assign a value in binary, octal, or hexadecimal systems by using the appropriate prefix. The prefix for binary is 0b, for octal is 0o, and for hexadecimal is 0x. If we repeat the previous example and assign a value in binary, we can see that the value is still an integer and the type of the value is int.

Convert a value to a different number system#
>>> value = 0b10000000
>>> print(value)
128
>>> print(int(value))
128
>>> type(value)
<class 'int'>

If we repeat the previous example and assign a value in octal, we can see that the value is still an integer and the type of the value is int. The same is true for hexadecimal.

The type of a value is an integer#
>>> value = 0o200
>>> type(value)
<class 'int'>
>>> value = 0x80
>>> type(value)
<class 'int'>

Convert a value to a different number system#

As we have seen, Python allows us to assign a value in a different numerical system. Python also provides built-in functions to convert a value to a different numerical system. We can use the hex, bin, and oct functions to convert a value to a hexadecimal, binary, or octal number, respectively.

Convert a value to a different number system#
>>> value = 0b10000000
>>> print(hex(value))
0x80
>>> print(bin(value))
0b10000000
>>> print(oct(value))
0o200

The hex, bin, and oct functions return a string representation of the value in the specified numerical system. The string representation includes the prefix for the numerical system. The hex function returns a string with the prefix 0x, the bin function returns a string with the prefix 0b, and the oct function returns a string with the prefix 0o.