Converting binary, hexadecimal, and octal strings to integers in Python is a common operation when working with different number representations. Each of these number systems has its own base and set of allowed digits. In this guide, we'll explore how to perform these conversions using Python.
1. Converting Binary Strings to Integers:
A binary string consists of only two digits: 0 and 1. You can use the built-in int() function in Python to convert a binary string to an integer by specifying the base 2 (binary) as the second argument.
Here's an example:
python code
binary_str = "1101"
decimal_num = int(binary_str, 2)
print(decimal_num) # Output: 13
In the example above, int(binary_str, 2) converts the binary string "1101" to its decimal equivalent, which is 13.
2. Converting Hexadecimal Strings to Integers:
A hexadecimal string consists of the digits 0-9 and the letters A-F (both uppercase and lowercase), representing values from 0 to 15. You can use the int() function with base 16 (hexadecimal) to convert a hexadecimal string to an integer.
Here's an example:
python code
hexadecimal_str = "1A"
decimal_num = int(hexadecimal_str, 16)
print(decimal_num) # Output: 26
In this case, int(hexadecimal_str, 16) converts the hexadecimal string "1A" to the decimal value, which is 26.
3. Converting Octal Strings to Integers:
An octal string consists of digits from 0 to 7. To convert an octal string to an integer, use the int() function with base 8 (octal).
Here's an example:
python code
octal_str = "35"
decimal_num = int(octal_str, 8)
print(decimal_num) # Output: 29
The int(octal_str, 8) function converts the octal string "35" to its decimal equivalent, which is 29.
Handling Exceptions:
When converting these strings to integers, you should handle exceptions for cases where the input string is not correctly formatted. For example, if a binary string contains characters other than '0' and '1', a ValueError will be raised. To handle exceptions gracefully, you can use a try and except block:
python code
binary_str = "11012"
try:
decimal_num = int(binary_str, 2)
print(decimal_num)
except ValueError:
print("Invalid binary string")
Summary:
Converting binary, hexadecimal, and octal strings to integers in Python is a straightforward process using the int() function. Specify the base of the input string as the second argument, and it will provide the integer representation. However, it's crucial to validate and handle exceptions to ensure that the input string is correctly formatted for the chosen base.#python4 #pythontutorial #pythonprogramming #python3 #pythonforbeginners #pythonlectures #pythonprograms #pythonlatest #rehanblogger #python4you #pythonlatestversion #pythonlatestversion Learn python3.12.0 and latest version of python3.13. If you are searching for python3.13.0 lessons, you are at the right place as this course will be very helpful for python learners or python beginners.