Converting from binary to hex is just as easy, as it was from hex to binary. Both notations have a base that is an exact power of two (2 = 21 and 16 = 24). To do the conversion we can just substitute the corresponding values according to the table. However, we need to pad the binary number to a complete byte, before the actual conversion.
|Input the binary value||The hex result is|
Advertise on this site. I promise you will like the rates :)
Converting from binary to hex is a straightforward procedure. Just remember to do the necessary padding, before making the substitution. Here is how to do the calculations:
Here is a table that contains the binary to hex mappings:
101002 = ?16
101002 = 1 01002
1 01002 = 0001 01002
00012 = 116, 01002 = 416
101002 = 1416
1100011010100000002 = ?16
110001101010000000 = 11 0001 1010 1000 0000
11 0001 1010 1000 0000 = 0011 0001 1010 1000 0000
0011 0001 1010 1000 00002 = 31A8016
While converting from binary to hex is very easy on paper, it could get a bit tricky to code. The key here is to do the padding and the length calculations correctly. The rest of it is just string compare and copy.
Let's start with the input. We are
converting from one string type to another string. This means that we
are not limited by 32-64 bit numbers. We can convert as big numbers,
as we like. However, choosing a round size(like 50 or 100) for the
binary string is not a good idea, because the data usually comes in
complete bytes. For that reason, it is better to choose a size that
is a multiple of 8, like 64, 96, 128.
Once we read the input, it is time to begin the algorithm.
Note, that here we want to add zeros to a complete byte. This is, because it will be better for the output formatting of the hex value.
Padding with starting zeros is an easy task, if you apply a little smart arithmetic to calculate the necessary padding. Its length is determined only by the size of the left-most incomplete group(here we group by 8). If the group is complete, then we don't need to pad anything. If the group is of 3 digits, we need to add 5 0s before its start. To determine that size we use the formula:
padding = 8 - length % 8;
% 8 gives the number of digits in the left most group.
Once we know the padding size we allocate memory for the padded binary string. Then copy the zeros and the binary value. Finally we reset the pointer to the beginning and return the result.
Now we can convert that binary to hex. We determine the number of digits for the hexadecimal number with the formula:
I think, the comments explain it well
The next step is to allocate the memory and convert every group of 4 to its hex representation. That we do with the function valueOf, according to the table above.
Finally, we reset the hex pointer and print the result.
The conversion using this program looks like this:
If you liked this article, you also might want to look at: