The problem is to convert the given binary number to its equivalent hexadecimal number.
The input could be very large and may not fit even into unsigned long long int.
Input : 110001110 Output : 18E Input : 1111001010010100001.010110110011011 Output : 794A1.5B36
Memorize the value of a 4-digit binary number in hexadecimal from this if we don’t know the relation.
A simple approach is to first convert the binary number to decimal number and then convert decimal to hexadecimal.
An efficient approach for large numbers is to consider the binary input as a string of characters and then follow the steps:
- Get length of substring to the left and right of the decimal point(‘.’) as left_len and right_len.
- If left_len is not a multiple of 4 add min number of 0’s in the beginning to make length of left substring a multiple of 4.
- If right_len is not a multiple of 4 add min number of 0’s in the end to make length of right substring a multiple of 4.
- Now, from the left extract one by one substrings of length 4 and add its corresponding hex code to the result.
- If in between a decimal(‘.’) is ecountered then add it to the result.
Hexadecimal number = 794A1.5B36
Time Complexity: O(n), where n is the length of string.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
This article is attributed to GeeksforGeeks.org