没有使用模块,有没有更好的方法来做到这一点?

时间:2013-12-24 11:46:03

标签: python python-3.3

现在,我知道有一个模块可以轻松转换这些,但我想这样做只是为了看看我是否可以在不使用模块的情况下完成。我的一个问题是有更好的方法将字符串分成4位。

def TH2B():
HexBin =     {"0":"0000","1":"0001","2":"0010","3":"0011","4":"0100","5":"0101","6":"0110","7":"0111","8    ":"1000","9":"1001","A":"1010","B":"1011","C":"1100","D":"1101","E":"1110","F":"1111"}
UserInput = str(input("Type in your hexidecimal code, and use capitals: "))
for each in UserInput:
    print(HexBin[each], end="")

def TB2H():
    n = 0
    BinHex = {"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"}
    UserInput = str(input("Type in your binary code, must be divisable by 4: "))
    for each in range(int(len(UserInput)/4)):
            print(BinHex[UserInput[(0+n):(4+n)]], end="")
            n +=4

def menu():
    select = int(input("Do you want to (1) go from Hex to Bin or (2) go from Bin to Hex?: "))
    if select == 1:
            TH2B()
    if select == 2:
            TB2H()

def main():
    Run = menu()

main()

1 个答案:

答案 0 :(得分:3)

使用int将二进制数,十六进制数表示转换为int:

>>> int('ff', 16) # 16: hexadecimal
255

然后,使用formatstr.format转换为二进制,十六进制表示。

>>> format(255, 'b') # binary
'11111111'
>>> format(255, 'x') # hexadecimal
'ff'

如果您希望结果为零填充,则前置0n(n为数字)。

>>> format(5, '08b')
'00000101'
>>> format(5, '02x')
'05'