十六进制数的长度

Ash*_*tra 1 python counting

我们怎样才能在Python语言中获得十六进制数的长度?我尝试使用此代码,但即使这显示一些错误.

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))
Run Code Online (Sandbox Code Playgroud)

这里我只使用346作为十六进制数,但我的实际数字非常大,需要手动计算.

Ash*_*ary 7

使用功能hex:

>>> b = 0x346
>>> hex(b)
'0x346'
>>> len(hex(b))-2
3
Run Code Online (Sandbox Code Playgroud)

或使用字符串格式:

>>> len("{:x}".format(b))
3
Run Code Online (Sandbox Code Playgroud)


gui*_*dot 6

虽然使用字符串表示作为中间结果在简单方面有一些优点,但在某种程度上浪费了时间和内存。我更喜欢数学解决方案(返回没有任何 0x 前缀的纯数字):

from math import ceil, log

def numberLength(n, base=16): 
    return ceil(log(n+1)/log(base))
Run Code Online (Sandbox Code Playgroud)

+1 调整处理的事实是,对于您的数字基数的精确幂,您需要一个前导“1”。