Convert binary, octal, decimal, and hexadecimal in Python
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).
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.
In Python3.6 and later, you can insert underscores _ in numbers.Repeating the underscore _ raises an error, but you can insert as many as you like if it is not repeated.
The underscore _ can be used as a delimiter when there are many digits. For example, it is easier to read if you enter _ every four digits.
Convert a number to a binary, octal, and hexadecimal string
You can use the following functions to convert a number to a binary, octal, or hexadecimal string.
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.
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.
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'))
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (