One More Ciphering Challenge
I appreciate your efforts a lot! Here you are going to dive deeper into ciphering and the last issue for you is converting a number from a decimal numeral system to a hexadecimal one. Try to do it using strings😉.
You need to divide the number by 16, and take down the remainder of the division.
If the number is greater than 9, you need to find a match in letters.
Then you should calculate the received number and implement the first step to it.
You can stop if division results in 0.
Rewrite remainders in the reversed order.
# Implementing dictionary, but here the keys are numbers, because we are ciphering dictionary = {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"} # Defining the decimal number 64206 decimal_number = 64206 # The text should be realised here due to the reason that further the decimal number will be changed print("The number in decimal numeral system is:", decimal_number) # Creating a list for storing converted hex number hexadecimal_number = [] # The conformity for 0 in decimal numeration system is 0; hence, this condition implemented # The loop executes till the number is zero while decimal_number != 0: # Counting the remainder of division by 16 remainder = decimal_number % 16 # Appending the converted resulting number for creating hexadecimal number hexadecimal_number.append(str(dictionary[remainder])) # This operation allows to decrease number by 16 an work with integer part of new one decimal_number = decimal_number // 16 # Reversing the string hexadecimal_number = hexadecimal_number[::-1] # Concatenating elements hexadecimal_number = "".join(hexadecimal_number) # Printing the result print("The number in hexadecimal numeral system is:", hexadecimal_number)
Uppgift
Swipe to start coding
Time to hone your skills! Follow the algorithm and fill the gaps to receive a number in hex representation:
- Print the
decimal_number
variable. - Create an empty list for storing
hexadecimal_number
. - Define the loop which executes till the
decimal_number
is0
. - Count the
remainder
of divisiondecimal_number
by16
. - Make the string
hexadecimal_number
reversed. - Join all elements of the string
hexadecimal_number
.
Lösning
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 3. Kapitel 2