Hi Everyone :cool:
What is the best way to represent, modify, and perform calculations with hexadecimal values (for instance, byte addresses) in Python?
It seems every time I play with hex numbers, I'm always getting the result as a string or regular int type.

case in point: Let's say I have the value 0x00E2, and the value 0x0F80 and I want to AND both of them and have the result in hex - Does python offer a convenient way to do this?

Thanks in advance :-)

>>> hex(234235)
>>> int('0x392fb',16)
>>> 234235 << 4
>>> hex(_)
>>> a=0x00E2
>>> b=0x0F80
>>> print hex(a & b)
simple and useful

The best way is to use the constructor 'int' with basis 16 to convert the hex values to integers, then use the bitwise operators &, |, ^ to perform the bitwise operations and use the 'hex' function to get the hexadecimal representation of the resulting integers. Here is an example with python 3 (but it also works with python 2)

>>> x, y = int("0x00E2", 16), int("0x0F80", 16)
>>> print(hex(x & y))
>>> print(x, y, x & y)
226 3968 128
>>> print(hex(x | y))
>>> print(x | y)
>>> print(bin(x), bin(y), bin(x&y), bin(x|y))
0b11100010 0b111110000000 0b10000000 0b111111100010
This question has already been answered. Start a new discussion instead.