Reputation: 1231
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 )
Upvotes: 58
Views: 302690
Reputation: 11
what about this one: using a proper mathematical formula. and a solid algorithm
Image to check how it works-->
def decimal_to_hexadecimal(value):
"""Converts decimal value to hexadecimal representation."""
# x = q * 16 + r
value = str(value)
mapping = {"10": "A", "11": "B", "12": "C", "13": "D", "14": "E", "15": "F"}
result = []
x = 2 # starting from 2 because we might have 0.25 and 0.0 at the same
while x > 1: # time which cause inconsistient hex transformations
x = int(value) / 16
res = int(value) - (int(x) * 16)
if mapping.get(str(res)):
result.append(str(mapping[str(res)]))
else:
result.append(str(res))
value = x
result = "".join(result)
return "0x" + result[::-1] #reverse it
For a better understanding please view the second chapter's first and second subheading's of the book:
Computer Systems: A Programmer's Perspective by Randal Bryant
Upvotes: 0
Reputation: 1111
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.
Upvotes: 111
Reputation: 1
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
Upvotes: 0
Reputation: 101
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).
Upvotes: 2
Reputation: 1
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))
Upvotes: -2
Reputation: 833
you can use this method which uses slicing
output = hex(15)[2:]
which cuts out the first 2 characters (0x) from the output
Upvotes: 2
Reputation: 21
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
Upvotes: 1
Reputation: 9474
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']
Upvotes: 26
Reputation: 11
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_)
Upvotes: 1
Reputation: 1937
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'
Upvotes: 2
Reputation: 1
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.
Upvotes: 0
Reputation: 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
Upvotes: 0
Reputation: 1
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"),
Upvotes: 0
Reputation: 223
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).
Upvotes: 1
Reputation: 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.
Upvotes: -1
Reputation: 67
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]
Upvotes: 0
Reputation: 2235
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])
Upvotes: 0
Reputation: 71
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
Upvotes: 1
Reputation: 1797
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'
Upvotes: 15
Reputation: 781
If without '0x'
prefix:
'{0:x}'.format(int(dec))
else use built-in hex()
funtion.
Upvotes: 15
Reputation: 21
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
Upvotes: -1
Reputation: 3513
This isn't exactly what you asked for but you can use the "hex" function in python:
>>> hex(15)
'0xf'
Upvotes: 48
Reputation: 70552
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.
Upvotes: 0
Reputation: 601609
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"),
Upvotes: 26