![]() |
Hexadecimal representation is commonly used in computer science and programming, especially when dealing with low-level operations or data encoding. In Python, converting a hex string to an integer is a frequent operation, and developers have multiple approaches at their disposal to achieve this task. In this article, we will explore various methods to convert a hex string to an integer in Python, providing a comprehensive guide for Geeks. Python Convert Hex String To IntegerBelow are some of the ways by which we can convert hex string into integer in Python: Python Convert Hex String To Integer Using
|
hex_string = "1a" decimal_integer = int (hex_string, 16 ) print (decimal_integer) |
26
int()
with Base 0In this example, the hexadecimal string “0xfa22” is converted to an integer using the `int()` function with base 0, allowing automatic detection of the input string’s base. The resulting `decimal_integer` is 64034.
hex_string = "0xfa22" decimal_integer = int (hex_string, 0 ) print (decimal_integer) |
64034
In this example, the hexadecimal string “0xfe00” is converted to an integer using the `literal_eval()` function from the `ast` module. The resulting `ans` variable holds the decimal integer value 65024.
from ast import literal_eval hex_str = "0xfe00" ans = literal_eval(hex_str) print (ans) |
65024
In this example, the hexadecimal string “ff” is first converted to an integer using `int(hex_string3, 16)`, resulting in 255. Then, the integer is formatted as a decimal string using `format()` with base 10 (‘d’). Finally, the formatted string is converted back to an integer using `int()`, yielding the same decimal integer value of 255.
hex_string3 = "ff" decimal_integer3 = int ( format ( int (hex_string3, 16 ), 'd' )) print (decimal_integer3) |
255
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |