Skip to content

Commit 8b2d1b7

Browse files
jasper256cclauss
authored andcommitted
added decimal to hexadecimal conversion (#977)
* added decimal to hexadecimal conversion * fixed error occuring as more digits were needed
1 parent e2d9953 commit 8b2d1b7

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

conversions/decimal_to_hexadecimal.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
""" Convert Base 10 (Decimal) Values to Hexadecimal Representations """
2+
3+
# set decimal value for each hexadecimal digit
4+
values = {
5+
0:'0',
6+
1:'1',
7+
2:'2',
8+
3:'3',
9+
4:'4',
10+
5:'5',
11+
6:'6',
12+
7:'7',
13+
8:'8',
14+
9:'9',
15+
10:'a',
16+
11:'b',
17+
12:'c',
18+
13:'d',
19+
14:'e',
20+
15:'f'
21+
}
22+
23+
def decimal_to_hexadecimal(decimal):
24+
""" take decimal value, return hexadecimal representation as str """
25+
hexadecimal = ''
26+
while decimal > 0:
27+
remainder = decimal % 16
28+
decimal -= remainder
29+
hexadecimal = values[remainder] + hexadecimal
30+
decimal /= 16
31+
return hexadecimal
32+
33+
def main():
34+
""" print test cases """
35+
print("5 in hexadecimal is", decimal_to_hexadecimal(5))
36+
print("15 in hexadecimal is", decimal_to_hexadecimal(15))
37+
print("37 in hexadecimal is", decimal_to_hexadecimal(37))
38+
print("255 in hexadecimal is", decimal_to_hexadecimal(255))
39+
print("4096 in hexadecimal is", decimal_to_hexadecimal(4096))
40+
print("999098 in hexadecimal is", decimal_to_hexadecimal(999098))
41+
42+
if __name__ == '__main__':
43+
main()

0 commit comments

Comments
 (0)