54

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 )
ʇsәɹoɈ
  • 22,757
  • 7
  • 55
  • 61
Eric
  • 1,191
  • 5
  • 14
  • 17
  • See also: [Python: hex conversion always two digits](http://stackoverflow.com/q/11676864/562769) – Martin Thoma Jan 12 '17 at 20:28
  • Answers have to do with reinventing the wheel. For an answer to converting an integer to hexadecimal representation, see the [builtin "hex"](https://docs.python.org/3/library/functions.html#hex) – user Jan 11 '21 at 00:49

24 Answers24

103

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.

Halo
  • 1,730
  • 1
  • 8
  • 31
Rich
  • 1,031
  • 2
  • 7
  • 2
  • 3
    https://stackoverflow.com/a/35750576/8437974 [Martijn Pieter's](https://stackoverflow.com/users/100297/martijn-pieters) `format(15, 'x')` – Germa Vinsmoke Apr 21 '19 at 10:23
48

This isn't exactly what you asked for but you can use the "hex" function in python:

>>> hex(15)
'0xf'
Joseph Lisee
  • 3,439
  • 26
  • 21
26

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"),
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 7
    @Apostolos No, I don't think it is. What makes you think so? However, I think it's useful for the original poster of the question to learn how to fix their code, even though it's not the solution i'd recommend to go with in "real" code. – Sven Marnach Jan 06 '18 at 07:22
  • ChangeHex( n / 16 ) or ChangeHex( n // 16 ) ? – sortas Dec 20 '18 at 14:53
  • 2
    @sortas `n // 16` in Python 3. This answer was written for Python 2, and in that version the two are equivalent. (I tried to make the minimal change to the code in the question to make it work.) – Sven Marnach Dec 20 '18 at 15:43
26

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']
Lynch
  • 9,174
  • 2
  • 23
  • 34
20

I use

"0x%X" % n

where n is the decimal number to convert.

OGHaza
  • 4,795
  • 7
  • 23
  • 29
thanos
  • 723
  • 7
  • 9
15

If without '0x' prefix:

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

else use built-in hex() funtion.

nikioa
  • 771
  • 5
  • 6
15

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

cjahangir
  • 1,773
  • 18
  • 27
2

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).

Tomas
  • 71
  • 5
2

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'

Piotr
  • 1,777
  • 17
  • 24
2

you can use this method which uses slicing

output = hex(15)[2:]

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

Hyperx837
  • 773
  • 5
  • 13
1
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

Marty
  • 51
  • 7
1

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).

John Skeen
  • 223
  • 1
  • 5
  • 9
1
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_)
1

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

0

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])
Youngsup Kim
  • 2,235
  • 5
  • 13
  • 18
0
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]
Shiv Konar
  • 67
  • 2
  • 6
0
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"),
LarrySnyder610
  • 2,277
  • 12
  • 24
0

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
Tom Zych
  • 13,329
  • 9
  • 36
  • 53
0

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.

voithos
  • 68,482
  • 12
  • 101
  • 116
0

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.

csabinho
  • 1,579
  • 1
  • 18
  • 28
0
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
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 14 '22 at 01:22
-1

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
Chandler
  • 21
  • 1
-1
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.

MrLeeh
  • 5,321
  • 6
  • 33
  • 51
TXVXT
  • 1
-2

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))
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 21 '21 at 09:16