Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ) 
like image 636
Eric Avatar asked Apr 26 '11 20:04

Eric


People also ask

How do you convert decimal to hex?

Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.

How do you convert decimal to octal in Python?

# Python program to convert decimal into other number systems dec = 344 print("The decimal value of", dec, "is:") print(bin(dec), "in binary.") print(oct(dec), "in octal.") print(hex(dec), "in hexadecimal.")

How do you remove 0x from hex in Python?

Python: hex() function For the hexadecimal representation of a float value, use the hex() method of floats. The hexadecimal representation is returned as string and starts with the prefix '0x'. To remove the prefix, use slices to return the string starting from index 2: [2:].


2 Answers

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.

like image 141
Rich Avatar answered Oct 04 '22 14:10

Rich


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

>>> hex(15) '0xf' 
like image 26
Joseph Lisee Avatar answered Oct 04 '22 12:10

Joseph Lisee