CaptainNewfoundland
CaptainNewfoundland

Reputation: 23

Turning decimals into hexadecimals (without the `hex()` function)

Before I start anything I just want to say that I know about the hex() function and for this project I can't use it. Also with regards to the question asked here, I'm aware of it and I've tried that solution but could not get my code to work. It is a different situation as I am using multiple functions. That thread also does not discuss my second question.

I've got two problems:

  1. The code I have so far can turn a decimal into a hexadecimal. Where I get stuck is that when I print the hexadecimal it prints backwards.
  2. I want the output to read:

Enter decimal value: 589
589 is equal to 24D in hexadecimal

But when I have the line:

print(og_dec_value,"is equal to",getHexChar(hex_value),end="","in hexadecimal")

I get an error about end=""not being at the end. But if I remove end="" then it only prints out the first number of the hexadecimal and leaves out the rest.

Here's my code as it stands right now:

def main():
    decToHex(int(input("Enter decimal value: ")))

def decToHex(dec_value):
    while dec_value > 0:
        hex_value=dec_value%16
        dec_value=dec_value//16
        print(getHexChar(hex_value),end="")

def getHexChar(dec_digit):
    if dec_digit < 10:
        return dec_digit
    if dec_digit == 10:
        return "A"
    if dec_digit == 11:
        return "B"
    if dec_digit == 12:
        return "C"
    if dec_digit == 13:
        return "D"
    if dec_digit == 14:
        return "E"
    if dec_digit == 15:
        return "F"

main()

Upvotes: 2

Views: 5806

Answers (3)

zoubir ba
zoubir ba

Reputation: 1

print("{:02X}".format(2555))=====>9FB #as string

Upvotes: 0

Shadow_f0x
Shadow_f0x

Reputation: 11

First I made two functions, one that converts decimal to binary and the opposite :

def dec_to_bin(n):
    exp=0
    intsup = 2**exp
    bin_list = []
    while intsup < n:
        intsup = 2**exp
        exp += 1
    while exp >= 0:
        intsup = 2**exp
        if n - intsup >= 0 :
            n -= intsup
            bin_list.append(1)
        else:
            bin_list.append(0)
        exp -= 1

    bin_number = ""
    for i in bin_list:
        bin_number += str(i)
    bin_number = int(bin_number)
    return bin_number


def bin_to_dec(n):
    dec=0
    while dec_to_bin(dec) != n :
        dec+=1
    return dec

Next, I made this short function that converts a decimal number between 0 and 15 to hex.

def hexshort(nbr):
    letters = ['A','B','C','D','E','F']
    for letter_num in range(len(letters)):
        if (10 + letter_num) == nbr:
            n=letters[letter_num]
    return nbr

Lastly, I made the function you need (converts any decimal number to hex), we need the functions before because, in this function, at some point we convert decimal to binary, then binary to decimal and finaly we use the short version.

def hexconv(nbr):
    nbr = dec_to_bin(nbr)
    binary_list = []
    nbr = str(nbr)
    for i in nbr:
        binary_list.append(i)
    longueur = len(binary_list)

    while longueur%4 != 0:
        binary_list.insert(0,'0')
        longueur=len(binary_list)

    half_oct = longueur/4
    half_oct = int(half_oct)
    half_oct_list = []
    half_oct_temp_list = []
    for j in range(half_oct):
        while len(half_oct_list)!= half_oct:
            half_oct_temp_list = binary_list[0:4]
            for k in range(4):
                binary_list.pop(0)
            half_oct_list.append(half_oct_temp_list)

    mini_list = []
    for m in range(len(half_oct_list)):
        values = ''
        for n in range(len(half_oct_list[m])):
            values += half_oct_list[m][n]
        mini_list.append(values)

    val = ''
    for c in range(len(mini_list)):
        mini_list[c] = int(mini_list[c])
        mini_list[c] = bin_to_dec(mini_list[c])
        mini_list[c] = hexshort(mini_list[c])
        mini_list[c] = str(mini_list[c])
        val += mini_list[c]
    return val

Exemple of what the function does with nbr = 1440 :

1440 : dectobin
    10110100000
    [0101, 1010, 0000]
    bintodec :
        5 10 0
    hexa :
        5A0

Ps : I know that you could use the build in function to convert decimal to binary and binary to decimal, I just wanted to challenge myself and not use them.

Upvotes: 1

Ondrej K.
Ondrej K.

Reputation: 9664

While getHexChar returns a single character string, decToHex does print individual digits on the fly instead. Minimal change to get your expected output out of your code could be:

def main():
    og_dec_value = int(input("Enter decimal value: "))
    print(og_dec_value,"is equal to",decToHex(og_dec_value), "in hexadecimal")

def decToHex(dec_value):
    ret_val = str()
    while dec_value > 0:
        hex_value=dec_value%16
        dec_value=dec_value//16
        ret_val = getHexChar(hex_value) + ret_val
    return ret_val

def getHexChar(dec_digit):
    if dec_digit < 10:
        return str(dec_digit)
    if dec_digit == 10:
        return "A"
    if dec_digit == 11:
        return "B"
    if dec_digit == 12:
        return "C"
    if dec_digit == 13:
        return "D"
    if dec_digit == 14:
        return "E"
    if dec_digit == 15:
        return "F"

main()

That out of the way. I really am not sure what the problem with hex() is. And if I was looking for another way of converting into hex string representation, I would (as suggested by Moinuddin Quadri) opt for corresponding formatting '{0:x}'.format(int(dec)) or '%x' % int(dec) if you'd prefer the older style (you probably should not).

If that is still now what you want and you wanted to maintain your course of cation, you could at least significantly simplify the getHexChar() for instance by doing this:

def getHexChar(dec_digit):
    return '{:x}'.format(range(16)[dec_digit])

Or we formatting really is an anathema:

def getHexChar(dec_digit):
    return str((tuple(range(10)) + ('a', 'b', 'c', 'd', 'e', 'f'))[dec_digit])

Upvotes: 0

Related Questions