2015-11-08 279 views
1
#Conversion from Hex to Bin 
def gethex(hexadecimal1): 
     numbintotal=' ' 
     for i in range(len(hexadecimal1)):    
       numbin1=hexadecimal1[i] 
       if(numbin1=='0'): 
        result='0000' 
       elif(numbin1=='1'): 
        result='0001' 
       elif(numbin1=='2'): 
        result='0010' 
       elif(numbin1=='3'): 
        result='0011' 
       elif(numbin1=='4'): 
        result='0100' 
       elif(numbin1=='5'): 
        result='0101' 
       elif(numbin1=='6'): 
        result='0110' 
       elif(numbin1=='7'): 
        result='0111' 
       elif(numbin1=='8'): 
        result='1000' 
       elif(numbin1=='9'): 
        result='1001' 
       elif(numbin1=='a'): 
        result='1010' 
       elif(numbin1=='b'): 
        result='1011' 
       elif(numbin1=='c'): 
        result='1100' 
       elif(numbin1=='d'): 
        result='1101' 
       elif(numbin1=='e'): 
        result='1110' 
       elif(numbin1=='f'): 
        result='1111' 
       elif(numbin1=='q'): 
#Get hexadecimal 
while(numhex!='q'): 
    numhex=raw_input('Enter a hexadecimal number (q to quit): ') 
    numbin= gethex(numhex) 
    if(numhex=='q'): 
     print(numbin) 
    else: 
     print('The binary number is:'+ numbin) 


        result='Program shutting down...' 
       else: 
        result='Please type in a hexadecimal number' 
       numbintotal= numbintotal + result 
     return numbintotal 


#Create a varaible 
numhex='0' 
results='0' 
numbin1='0' 

我得到如何從十六進制轉換爲二進制如上所示,但我不知道如何做到另一種方式做二進制到十六進制?請注意,你不能使用任何Python函數,因爲這只是一個簡單的方法,所以我只是讓你知道!我正在考慮在代碼中完全相反,例如numbin1 == 0001和result = 1.請幫助我,非常感謝!這是在PYTHON 2.7!二進制到十六進制轉換

回答

0

試試這個功能了。

# "Copyright Notice", please do not remove. 
# Written by Kevin Ng 
# The full tutorial on this subject can be found @ http://kevinhng86.iblog.website or http://programming.world.edu. 
# This source code file is a part of Kevin Ng's Z library. 
# This source code is licenses under CCDL-1.0 A copy of CDDL1.0 can be found at https://opensource.org/licenses/CDDL-1.0 
# End "Copyright Notice" 
def binhexZ(invalue): 
    wmap = {"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" 
      } 
    i = 0 
    output = "" 

    while (len(invalue) % 4 != 0): 
     invalue = "0" + invalue 

    while (i < len(invalue)): 
     output = output + wmap[invalue[i:i + 4]] 
     i = i + 4 

    output = output.lstrip("0") 
    output = "0" if len(output) == 0 else output 

    return output 
相關問題