Is there a way to do math with hexadecimal numbers in Python?

Since hexadecimal numbers are really strings representing a numeric value, you best convert these strings to a denary (base 10) number, do the mathematical operation and change the result back to the hexadecimal. Here is an example ...

def add_hex2(hex1, hex2):
    """add two hexadecimal string values and return as such"""
    return hex(int(hex1, 16) + int(hex2, 16))

print add_hex2('0xff', '0xff')  # 0x1fe
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.