![]() |
|
[Tut] Hex String to Hex Integer in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Hex String to Hex Integer in Python (/thread-100161.html) |
[Tut] Hex String to Hex Integer in Python - xSicKxBot - 10-30-2022 Hex String to Hex Integer in Python 5/5 – (1 vote) ![]() Question: Given a hexadecimal string such as Code: '0xf'The hexadecimal string representation with the Code: '0x'Code: 16In this article, I’ll show you how to do some basic conversion and arithmetic computations using the hexadecimal format. So, let’s get started! ![]() Convert Hex to Decimal using int() You can convert any hexadecimal string to a decimal number using the Code: int()Code: base=16Code: '0xf'Code: int('0xf', base=16)Code: int('0xf', 16)Code: >>> int('0xf', base=16)
15
>>> int('0xf', 16)
15Note that you can also write the hexadecimal number without the string quotes like so: Code: >>> 0xf
15The Code: 0xUsing the eval() Function ![]() That’s why an alternative way to convert a hexadecimal string to a numerical value (integer, base 10) is to use the Code: eval('0xf')Code: >>> eval('0xf')
15However, I wouldn’t recommend it over the Code: int()Code: eval()Hex Arithmetic Operators You can simply add or subtract two hexadecimal numbers in Python by using the normal Code: +Code: -Code: >>> 0xf + 0x1
16
>>> 0xf - 0xa
5
>>> 0x1 + 0x1
2The result is always shown in decimal values, i.e., with Code: base=10You can display the result with Code: base=16Code: hex()Code: hex(0x1 + 0x1)Code: '0x2'Here are a couple of examples: Code: >>> hex(0x1 + 0x1) '0x2'
>>> hex(0xf + 0xf) '0x1e'
>>> hex(0xf * 16) '0xf0'In the last line, you multiply with the base Code: 16Code: 10Adding Two Hex Strings ![]() In the following example, you add together two hex strings Code: '0xf'Code: '0xf'Code: >>> int('0xf', 16) + int('0xf', 16)
30If you need the result as a hex string, you can pass the whole computation into the Code: hex()Code: 30Code: >>> hex(int('0xf', 16) + int('0xf', 16)) '0x1e'You can also subtract or multiply two hex strings by converting them to integers from their base Code: 16Code: int(hex_str, 16)Code: -Code: *Code: hex()See here: Code: >>> h1 = '0xf'
>>> h2 = '0x1'
>>> h1_int = int(h1, 16)
>>> h2_int = int(h2, 16)
>>> hex(h1_int - h2_int) '0xe'
>>> hex(h1_int * h2_int) '0xf'To print the hexadecimal string such as Code: '0xffffff'Code: '0x'Code: hex_string[2:]A minimal example: Code: >>> hex_string = '0xfffffff'
>>> hex_string[2:] 'fffffff'![]() Thanks for reading through the whole article, I’d love to see you around more often in the Finxter community to learn and improve your coding skills. ![]() If you also want to learn, join our free email academy and download our cheat sheets here: |