所以这是我创建的代码和字典:
def dectohex (number, dectohex_table):
final_dectohex=''
if number in dectohex_table:
final_dectohex+=dectohex_table[number]
print(final_dectohex)
dectohex_table={'0':'0', '1':'1', '2':'2', '3':'3', '4':'4', '5':'5', '6':'6', '7':'7', '8':'8', '9':'9', '10':'A', '11':'B', '12':'C', '13':'D'
, '14':'E', '15':'F'}
有没有办法使用这个代码使用字典(因为我们必须),但要转换高于15的数字?
答案 0 :(得分:4)
我猜这是功课(因为python内置了hex
功能)
你应该研究的是模运算%和循环:)
我不想拼出来,但考虑一下如何使用模数打破基数为16的数字。
提示: 请尝试以下方法:
print(423 % 10)
print( (423/10) % 10)
print( ((423/10)/10) % 10)
答案 1 :(得分:1)
table = {0:'0', 1:'1', 2:'2', 3:'3', 4:'4', 5:'5', 6:'6', 7:'7', 8:'8', 9:'9', 10:'A', 11:'B', 12:'C', 13:'D', 14:'E', 15:'F'}
def dectohex(num, tab):
value = num
s = ''
while value > 0:
s += table[value % 16]
value //= 16
return '0x' + ''.join(reversed(s))
>>> dectohex(123456, table) # the above function
'0x1E240'
>>> hex(123456) # python's function
'0x1e240'
答案 2 :(得分:1)
将这个单行程转入..
>>> x=423
>>> ''.join([ {'0000':'0','0001':'1','0010':'2','0011':'3','0100':'4','0101':'5',
'0110':'6','0111':'7','1000':'8','1001':'9','1010':'a','1011':'b',
'1100':'c','1101':'d','1110':'e','1111':'f'}[y]
for y in re.findall('....', ''.join(map(str, [ int(x&(1<<i)>0)
for i in range(32) ][::-1]))) ])
'000001a7'