Length of hexadecimal number

13,267

Solution 1

Use the function hex:

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

or using string formatting:

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

Solution 2

While using the string representation as intermediate result has some merits in simplicity it's somewhat wasted time and memory. I'd prefer a mathematical solution (returning the pure number of digits without any 0x-prefix):

from math import ceil, log

def numberLength(n, base=16): 
    return ceil(log(n+1)/log(base))

The +1 adjustment takes care of the fact, that for an exact power of your number base you need a leading "1".

Solution 3

As Ashwini wrote, the hex function does the hard work for you:

hex(x)

Convert an integer number (of any size) to a hexadecimal string. The result is a valid Python expression.

Share:
13,267
Ashray Malhotra
Author by

Ashray Malhotra

Updated on June 14, 2022

Comments

  • Ashray Malhotra
    Ashray Malhotra about 2 years

    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.