3. [3 points] This problem will explore hexadecimal notation. (a) (2 points) Wri
ID: 3599567 • Letter: 3
Question
3. [3 points] This problem will explore hexadecimal notation. (a) (2 points) Write a function hex string_to_bin_ string(hex_string) (in hex string to_bin_string.py) that converts a non-empty string containing the hexadecimal representation of a number (using the characters "O""9" and "A" "F" as digits) into a string containing that number's binary representation. General algorithm: Start with an empty string for your result. Use a loop with a variable i to access the ith character of the string. Inside the loop, convert this 'hexadecimal' character to its corresponding 4-bit binary string and concatenate that to the result. Once all hex characters are converted, return the result. You can convert the hexadecimal character to the binary pattern using 16 different if statements, but there is a much shorter way. Can you see it? It involves using this list: [" 0000", "0001", "0010", .., "1110", "1111" ] Example usage: >python3 -i hex_string_to_bin_string.py >>> hex_string to_bin_string("2" 0010' >>> hex_string to bin string("A") 1010' >>> hex_string to bin string("2A" ) 00101010" >>> hex_string_to_bin string("2AC") 001010101100Explanation / Answer
def hex_string_to_bin_string(hex_string):
result = ""
hex_dig = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
bin_for_hex = ["0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"]
for i in hex_string:
result += bin_for_hex[hex_dig.index(i)]
return result
def bin_string_to_int(bin_string):
decimal = 0
for d in bin_string:
decimal = decimal*2 + int(d)
return decimal
def hex_string_to_int(s):
bin_string = hex_string_to_bin_string(s)
return bin_string_to_int(bin_string)
# copy pastable code link: https://paste.ee/p/VKqjF
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.