[英]convert from decimal to HEX in python
我有一個簡單的任務,我要求用戶輸入16位十六進制數,但如果用戶輸入一個十進制數,我想為它們轉換它。 如果它不是16位HEX,我會編寫代碼來重新詢問輸入,但是我想添加從Decimal到HEX的轉換,然后驗證它是16位HEX數。
我想我只需要在正確的方向上進行轉換。
謝謝大家!
你可以使用內置的hex()
:
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
它返回一個前綴為0x
的字符串,因此您需要切掉前兩個字符或檢查長度是否為16 + 2。
此外,如果您的用戶輸入不是整數,則需要轉換它。 這就是我寫整篇文章的方式:
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
使用內置的hex()
:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.