[python] Python convert decimal to hex

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 )

This question is related to python function decimal hex

The answer is


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


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

>>> hex(15)
'0xf'

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']

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'


I use

"0x%X" % n

where n is the decimal number to convert.


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). Some examples can be found here.


If without '0x' prefix:

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

else use built-in hex() funtion.


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.


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


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


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.


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]

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

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


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.


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

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

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"),

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

What about this:

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

Example:

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

~Rich

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


To get a pure hex value this might be useful. It's based on Joe's answer:

def gethex(decimal):
    return hex(decimal)[2:]

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to decimal

Java and unlimited decimal places? What are the parameters for the number Pipe - Angular 2 Limit to 2 decimal places with a simple pipe C++ - Decimal to binary converting Using Math.round to round to one decimal place? String to decimal conversion: dot separation instead of comma Python: Remove division decimal Converting Decimal to Binary Java Check if decimal value is null Remove useless zero digits from decimals in PHP

Examples related to hex

Transparent ARGB hex value How to convert a hex string to hex number Javascript: Unicode string to hex Converting Hexadecimal String to Decimal Integer Convert string to hex-string in C# Print a variable in hexadecimal in Python Convert ascii char[] to hexadecimal char[] in C Hex transparency in colors printf() formatting for hex Python Hexadecimal