Search code examples
pythonpython-3.xp2p

Is there a way to do math with hexadecimals in Python 3?


I'm working with P2P and would like to allow peers a way to find each other. I'm structuring my network where each peer has an ideal set of peers to look for in the network. The IDs of these peers are in hexadecimal format. While in the network, a node constantly searches for peers who have IDs which are closest to it's ideal location (based on its own peer-id).

The easiest way to see who is closest and find other peers in the network is to treat the IDs as if they are numbers. Converting to ints before performing mathematical operations would severely complicate things.


Solution

  • >>> a = 0xA
    >>> b = 0xa
    >>> a + b
    20
    >>> hex(a + b)
    '0x14'