Search code examples
pythoncounting

Length of hexadecimal number


How can we get the length of a hexadecimal number in the Python language? I tried using this code but even this is showing some error.

i = 0
def hex_len(a):
    if a > 0x0:
        # i = 0
        i = i + 1
        a = a/16
        return i
b = 0x346
print(hex_len(b))

Here I just used 346 as the hexadecimal number, but my actual numbers are very big to be counted manually.


Solution

  • Use the function hex:

    >>> b = 0x346
    >>> hex(b)
    '0x346'
    >>> len(hex(b))-2
    3
    

    or using string formatting:

    >>> len("{:x}".format(b))
    3