-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConvertToHex.py
71 lines (58 loc) · 1.86 KB
/
ConvertToHex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from ConvertToDec import convert_to_dec
'''
reverse_str is a function that takes a string s,
and returns it reversed, using a slicing method
'''
def reverse_str (s):
return s [::-1]
'''
convert_remainder is a function that takes the remainder (int),
converts it to a hexadecimal notation, and returns it (string).
'''
def convert_remainder (remainder):
coefficients = "0123456789abcdef"
return coefficients [remainder]
'''
convert_dec_to_hex is a function that takes a string n
(containing a number in decimal notation), that
converts it to a hexadecimal notation, and that
returns it (as a string)
'''
def convert_dec_to_hex (n):
converted_n = ""
while True:
result, remainder = divmod (int (n), 16)
converted_n += convert_remainder (remainder)
if result == 0:
break
n = result
converted_n = reverse_str (converted_n)
return converted_n
'''
convert_bin_to_hex is a function that takes a string b
(containing a binary number), converts it to hexadecimal,
and returns it (as a string)
'''
def convert_bin_to_hex (b):
n = convert_to_dec (b, "bin")
return convert_dec_to_hex (n)
'''
convert_to_hex is a function that takes a string n, and
a string called base. This function converts n in
hexadecimal depending on the string base.
It returns ultimately a string containing the hexadecimal
notation of n.
'''
def convert_to_hex (n, base):
if base == "dec":
return convert_dec_to_hex (n)
elif base == "bin":
return convert_bin_to_hex (n)
elif base == "hex":
return str (n)
else:
return "ERROR : NOT A SUPPORTED BASE YET. IT FUNCTIONS ONLY FOR bin/dec/hex BASES ONLY"
if __name__ == "__main__":
print (convert_to_hex ("1988971", "dec"))
print (convert_to_hex ("1ae867f987d", "hex") == "1ae867f987d")
print (convert_to_hex ("100100101", "bin") == "125")