Length of hexadecimal number

Question:

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.

Asked By: Ashray Malhotra

||

Answers:

Use the function hex:

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

or using string formatting:

>>> len("{:x}".format(b))
3
Answered By: Ashwini Chaudhary

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.

Answered By: Justin Ethier

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”.

Answered By: guidot
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.