Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of hexadecimal number [duplicate]

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.

like image 549
Ashray Malhotra Avatar asked Nov 24 '25 08:11

Ashray Malhotra


2 Answers

Use the function hex:

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

or using string formatting:

>>> len("{:x}".format(b))
3
like image 107
Ashwini Chaudhary Avatar answered Nov 25 '25 20:11

Ashwini Chaudhary


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

like image 44
guidot Avatar answered Nov 25 '25 21:11

guidot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!