Last active
June 29, 2022 17:11
-
-
Save econchick/4666389 to your computer and use it in GitHub Desktop.
Convert decimal/base 10 numbers to hexidecimal/base 16
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def hex2dec(dec_number): | |
mapping = { | |
10 : "A", | |
11 : "B", | |
12 : "C", | |
13 : "D", | |
14 : "E", | |
15 : "F" | |
} | |
remainders = [] | |
Q = dec_number | |
while Q > 0: | |
Q = dec_number / 16 | |
R = (dec_number % 16) | |
if R > 9: | |
remainders.append(mapping[R]) | |
else: | |
remainders.append(R) | |
dec_number = Q | |
remainders = remainders[::-1] | |
hex = "0x" | |
for item in remainders: | |
hex.join(item) | |
return hex | |
hex2dec(954) | |
iteration 1: Q = 59, R = 10, A | |
remainders = ["A"] | |
dec_number = 59 | |
iteration 2: 59/16 = 3, R = 11, B | |
remainders = ["A", "B"] | |
dec_number = 3 | |
iteration 3: 3/16 = 0, R = 3, 3 | |
remainers = ["A","B",3] | |
hex = 3BA |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment