Kieran Lavelle
Kieran Lavelle

Reputation: 446

Is there a better way to do this without the use of the module?

Now, I know there is a module to convert these easily but I wanted to do this just to see if I could do it without using the module. One of my questions is is there a better way to split the strings up into bits of 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()

Upvotes: 0

Views: 58

Answers (1)

falsetru
falsetru

Reputation: 369364

Convert binary number, hexadecimal number representation to int using int:

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

Then, use format or str.format to convert in to binary, hexadecimal representation.

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

Prepend 0n (n is number) if you want the result to be zero-padded.

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

Upvotes: 3

Related Questions