(Python) Binary to Hex
Binary to Hex (10 points): Binary numbers are numbers written in base two. Each digit is represented using only one of two symbols: 0 or 1. Decimal numbers are numbers written in base 10, and hexa-decimal (or hex) numbers are numbers written in base 16. Each digit in a hex number is one of either numbers 0 through 9, or the letters a, b, c, d, e and f that represent numbers 10 through 15 respectively. The decimal number 21 is written 10101 in binary, and 15 in hex. As another example, the number 31 is written 11111 in binary and 1f in hex. In this problem, please write a program binary-to-hex.py to convert a number written in binary to hex. In other words, receive a string containing a binary number from the user and print out the corresponding value in hexadecimal. While we talked previously in class about how to directly convert to and from different bases, we want to try a completely different approach. Since hexadecimal is base 16, or 2 4 , the conversion from binary to hex is actually very easy. Every four digits in a binary representation has an exact equivalent in a hex representation as shown in the following table. Binary Hex Binary Hex Binary Hex Binary Hex 0000 0001 0010 0011 0 1 2 3 0100 0101 0110 0111 4 5 6 7 1000 1001 1010 1011 8 9 a b 1100 1101 1110 1111 c d e f In order to convert the binary string 11111, first we prepend leading 0s to make the overall length of the input string divisble by 4 (in this case, 00011111). Then, we split it into group of fours starting from the least significant digits. So we group the binary digits as 0001 1111. Looking at the table we can convert each of these groups independently, 0001 turns into a 1 and 1111 turns into an f, therefore 1f is the hex representation. See below for sample input and output. Sample Input and Output: Enter a binary string: 10101001101011 The hex value of the string is 2a6b Consider using a dict for storing the binary strings and their corresponding hex values. Then loop through and convert each set of 4 characters in the input binary string to hex using the dict.
To get solution Buy and download