Python convert decimal to hex

Question:

I have a function here that converts decimal to hex but it prints it in reverse order. How would I fix it?

def ChangeHex(n):
    if (n < 0):
        print(0)
    elif (n<=1):
        print(n)
    else:
        x =(n%16)
        if (x < 10):
            print(x), 
        if (x == 10):
            print("A"),
        if (x == 11):
            print("B"),
        if (x == 12):
            print("C"),
        if (x == 13):
            print("D"),
        if (x == 14):
            print("E"),
        if (x == 15):
            print ("F"),
        ChangeHex( n / 16 )
Asked By: Eric

||

Answers:

This isn’t exactly what you asked for but you can use the “hex” function in python:

>>> hex(15)
'0xf'
Answered By: Joseph Lisee

If you want to code this yourself instead of using the built-in function hex(), you can simply do the recursive call before you print the current digit:

def ChangeHex(n):
    if (n < 0):
        print(0)
    elif (n<=1):
        print n,
    else:
        ChangeHex( n / 16 )
        x =(n%16)
        if (x < 10):
            print(x), 
        if (x == 10):
            print("A"),
        if (x == 11):
            print("B"),
        if (x == 12):
            print("C"),
        if (x == 13):
            print("D"),
        if (x == 14):
            print("E"),
        if (x == 15):
            print ("F"),
Answered By: Sven Marnach

Instead of printing everything in the function, you could just allow it to return the value in hex, and do whatever you want with it.

def ChangeHex(n):
    x = (n % 16)
    c = ""
    if (x < 10):
        c = x
    if (x == 10):
        c = "A"
    if (x == 11):
        c = "B"
    if (x == 12):
        c = "C"
    if (x == 13):
        c = "D"
    if (x == 14):
        c = "E"
    if (x == 15):
        c = "F"

    if (n - x != 0):
        return ChangeHex(n / 16) + str(c)
    else:
        return str(c)

print(ChangeHex(52))

There are probably more elegant ways of parsing the alphabetic components of the hex, instead of just using conditionals.

Answered By: voithos

I think this solution is elegant:

def toHex(dec):
    digits = "0123456789ABCDEF"
    x = (dec % 16)
    rest = dec // 16
    if (rest == 0):
        return digits[x]
    return toHex(rest) + digits[x]

numbers = [0, 11, 16, 32, 33, 41, 45, 678, 574893]
print [toHex(x) for x in numbers]
print [hex(x) for x in numbers]

This output:

['0', 'B', '10', '20', '21', '29', '2D', '2A6', '8C5AD']
['0x0', '0xb', '0x10', '0x20', '0x21', '0x29', '0x2d', '0x2a6', '0x8c5ad']
Answered By: Lynch

What about this:

hex(dec).split('x')[-1]

Example:

>>> d = 30
>>> hex(d).split('x')[-1]
'1e'

By using -1 in the result of split(), this would work even if split returned a list of 1 element.

Answered By: Rich

I use

"0x%X" % n

where n is the decimal number to convert.

Answered By: thanos

non recursive approach to convert decimal to hex

def to_hex(dec):

    hex_str = ''
    hex_digits = ('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F')
    rem = dec % 16

    while dec >= rem:
        remainder = dec % 16
        quotient = dec / 16
        if quotient == 0:
            hex_str += hex_digits[remainder]
        else:
            hex_str += str(remainder)
        dec = quotient

    return hex_str[::-1] # reverse the string
Answered By: Chandler

If without '0x' prefix:

'{0:x}'.format(int(dec))

else use built-in hex() funtion.

Answered By: nikioa

Python’s string format method can take a format spec.

From decimal to binary

"{0:b}".format(154)
'10011010'

From decimal to octal

"{0:o}".format(154)
'232'

From decimal to hexadecimal

"{0:x}".format(154)
'9a'

Format spec docs for Python 2

Format spec docs for Python 3

Answered By: cjahangir
def main():
    result = int(input("Enter a whole, positive, number to be converted to hexadecimal: "))
    hexadecimal = ""
    while result != 0:
        remainder = changeDigit(result % 16)
        hexadecimal = str(remainder) + hexadecimal
        result = int(result / 16)
    print(hexadecimal)

def changeDigit(digit):
    decimal =     [10 , 11 , 12 , 13 , 14 , 15 ]
    hexadecimal = ["A", "B", "C", "D", "E", "F"]
    for counter in range(7):
        if digit == decimal[counter - 1]:
            digit = hexadecimal[counter - 1]
    return digit

main()

This is the densest I could make for converting decimal to hexadecimal.
NOTE: This is in Python version 3.5.1

Answered By: Marty

A version using iteration:

def toHex(decimal):
    hex_str = ''
    digits = "0123456789ABCDEF"
    if decimal == 0:
       return '0'

    while decimal != 0:
        hex_str += digits[decimal % 16]
        decimal = decimal // 16

    return hex_str[::-1] # reverse the string

numbers = [0, 16, 20, 45, 255, 456, 789, 1024]
print([toHex(x) for x in numbers])
print([hex(x) for x in numbers])
Answered By: Youngsup Kim
hex_map = {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 to_hex(n):
    result = ""
    if n == 0:
        return '0'
    while n != 0:
        result += str(hex_map[(n % 16)])
        n = n // 16
    return '0x'+result[::-1]
Answered By: Shiv Konar
dec = int(input("Enter a number below 256: "))
hex1 = dec // 16

if hex1 >= 10:
    hex1 = hex(dec)

hex2 = dec % 16
if hex2 >= 10:
    hex2 = hex(hex2)

print(hex1.strip("0x"))

Works well.

Answered By: TXVXT

Apart from using the hex() inbuilt function, this works well:

letters = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F']
decimal_number = int(input("Enter a number to convert to hex: "))
print(str(letters[decimal_number//16])+str(letters[decimal_number%16]))

However this only works for converting decimal numbers up to 255 (to give a two diget hex number).

Answered By: John Skeen
n = eval(input("Enter the number:"))
def ChangeHex(n):
    if (n < 0):
        print(0)
    elif (n<=1):
        print(n),
    else:
        ChangeHex( n / 16 )
        x =(n%16)
        if (x < 10):
            print(x), 
        if (x == 10):
            print("A"),
        if (x == 11):
            print("B"),
        if (x == 12):
            print("C"),
        if (x == 13):
            print("D"),
        if (x == 14):
            print("E"),
        if (x == 15):
            print ("F"),
Answered By: Ermias Asmare

This is the best way I use it

hex(53350632996854).lstrip("0x").rstrip("L")
# lstrip helps remove "0x" from the left  
# rstrip helps remove "L" from the right 
# L represents a long number

Example:

>>> decimal = 53350632996854
>>> hexadecimal = hex(decimal).lstrip("0x")
>>> print(hexadecimal)
3085a9873ff6

if you need it Upper Case, Can use “upper function”
For Example:

decimal = 53350632996854
hexadecimal = hex(decimal).lstrip("0x").upper()
print(hexadecimal)
3085A9873FF6
Answered By: Mohammed Towfiq

In order to put the number in the correct order i modified your code to have a variable (s) for the output. This allows you to put the characters in the correct order.

s=""
def ChangeHex(n):
    if (n < 0):
        print(0)
    elif (n<=1):
        print(n)
    else:
        x =(n%16)
        if (x < 10):
            s=str(x)+s, 
        if (x == 10):
            s="A"+s,
        if (x == 11):
            s="B"+s,
        if (x == 12):
            s="C"+s,
        if (x == 13):
            s="D"+s,
        if (x == 14):
            s="E"+s,
        if (x == 15):
            s="F"+s,
        ChangeHex( n / 16 )        

NOTE: This was done in python 3.7.4 so it may not work for you.

Answered By: Aryan Kainth

It is good to write your own functions for conversions between numeral systems to learn something. For "real" code I would recommend to use build in conversion function from Python like bin(x), hex(x), int(x).

Answered By: Tomas

If you need even numbers of chars to be returned, you can use:

def int_to_hex(nr):
  h = format(int(nr), 'x')
  return '0' + h if len(h) % 2 else h

Example

int_to_hex(10) # returns: '0a'

and

int_to_hex(1000) # returns: '03e8'

Answered By: Piotr
def tohex(dec):
    x = (dec%16)
    igits = "0123456789ABCDEF"
    digits = list(igits)
    rest = int(dec/16)
    if (rest == 0):
        return digits[x]
    return tohex(rest) + digits[x]

numbers = [0,16,32,48,46,2,55,887]
hex_ = ["0x"+tohex(i) for i in numbers]
print(hex_)
Answered By: blackhumdinger

I recently made this python program to convert Decimal to Hexadecimal, please check this out. This is my first Answer in stack overflow .

decimal = int(input("Enter the Decimal no that you want to convert to Hexadecimal : "))
intact = decimal
hexadecimal = ''
dictionary = {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'}

while(decimal!=0):
    c = decimal%16 
    hexadecimal =  dictionary[c] + hexadecimal 
    decimal = int(decimal/16)

print(f"{intact} is {hexadecimal} in Hexadecimal")

When you Execute this code this will give output as:

Enter the Decimal no that you want to convert to Hexadecimal : 2766

2766 is ACE in Hexadecimal

Answered By: Kushal Nagwanshi

you can use this method which uses slicing

output = hex(15)[2:]

which cuts out the first 2 characters (0x) from the output

Answered By: Hyperx837

This code is Incomplite/- Max input is 159

def DicToHex(lsdthx, number, resault):
   bol = True
   premier = 0
   for i in range(number):
      for hx in lsdthx:
        if hx <= number:
            if number < 16:
                if hx > 9:
                    resault += lsdthx[hx]
                else:
                    resault += str(lsdthx[hx])
                number -= hx
            else:
                while bol:
                    if number - 16 >= 0:
                        number -= 16
                        premier += 1
                    else:
                        resault += str(premier)
                        bol = False
      return resault

dthex = {15:'F', 14:'E', 13:'D', 12:'C', 11:'B', 10:'A', 9:9, 8:8, 7:7,6:6, 5:5, 4:4, 3:3, 2:2, 1:1}
reslt = ''
num = int(input('enter dicimal number : '))
print(DicToHex(dthex, num, reslt))
Answered By: Wahil Chettouf
def decimal_to_base(decimal_number, destination_base):
digits_array = []
hexadecimals = {10:"A", 11:"B", 12:"C", 13:"D", 14:"E", 15:"F"}
while decimal_number > 0:
    rest = decimal_number % destination_base
    if rest in hexadecimals:
        rest = hexadecimals[rest]
    digits_array.insert(0, rest)
    decimal_number = decimal_number // destination_base
return digits_array
Answered By: Carlos Sosa
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.