2 回答

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以只使用hex()內(nèi)置的:
In [23]: hex(187)
Out[23]: '0xbb'
In [24]: hex(123456789)
Out[24]: '0x75bcd15'
In [25]: len(hex(123456789)[2:])
Out[25]: 7
In [26]: len(hex(123456789)) - 2
Out[26]: 7
它會返回一個(gè)以開頭的字符串0x,因此您需要將前兩個(gè)字符切掉,或者檢查其長度為16 + 2。
另外,如果您的用戶輸入的內(nèi)容還不是整數(shù),則需要對其進(jìn)行轉(zhuǎn)換。這是我寫整個(gè)事情的方法:
def your_function(dec, length=16):
try:
# Converts the string into an integer
# If dec is already an integer, it won't throw any errors
n = int(dec)
return len(hex(n)[:2]) == length
except ValueError:
# int(dec) raised the error. It's not a number.
return False

TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
使用hex()內(nèi)置的:
def check_hex_length(decimal_number):
hex_number = hex(decimal_number) # hex_number now contains your number as hex.
return (len(hex_number) - 2) == 16
添加回答
舉報(bào)