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)
'0x392fb'
>>> int('0x392fb',16)
234235
>>> 234235 << 4
3747760
>>> hex(_)
'0x392fb0'
>>> a=0x00E2
>>> b=0x0F80
>>> print hex(a & b)
0x80
>>>``````
commented: simple and useful +1

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))
0x80
>>> print(x, y, x & y)
226 3968 128
>>> print(hex(x | y))
0xfe2
>>> print(x | y)
4066
>>> print(bin(x), bin(y), bin(x&y), bin(x|y))
0b11100010 0b111110000000 0b10000000 0b111111100010``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.