问题
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 )
回答1:
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"),
回答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.
回答3:
This isn't exactly what you asked for but you can use the "hex" function in python:
>>> hex(15)
'0xf'
回答4:
I think this solution is elegant:
def toHex(dec):
x = (dec % 16)
digits = "0123456789ABCDEF"
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']
回答5:
I use
"0x%X" % n
where n
is the decimal number to convert.
回答6:
If without '0x'
prefix:
'{0:x}'.format(int(dec))
else use built-in hex()
funtion.
回答7:
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
回答8:
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.
回答9:
To get a pure hex value this might be useful. It's based on Joe's answer:
def gethex(decimal):
return hex(decimal)[2:]
回答10:
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
回答11:
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).
回答12:
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.
回答13:
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])
回答14:
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]
回答15:
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"),
回答16:
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
回答17:
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.
回答18:
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
回答19:
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.
来源:https://stackoverflow.com/questions/5796238/python-convert-decimal-to-hex