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 )
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.
# 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.")
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:].
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.
This isn't exactly what you asked for but you can use the "hex" function in python:
>>> hex(15) '0xf'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With