The decimal to binary converter takes a number in decimal number system and converts it to its representation in binary system. I created an online tool that you can use freely. Then you can learn how to build such converter yourself and use the online tool to check if your program works correctly.
|Input the decimal number||The binary representation is|
Before you can create a decimal to binary converter, you need to know about the different number systems and how they work. The algorithm to convert a number from decimal to other system is very simple:
Here is an example with decimal to binary:
610 = ? (bin)
Step 1: 6 / 2 = 3 and remainder 0. Now
we save the result(2) and the remainder (1).
Repeat step 1, using the result: 3 / 2 = 1 and remainder 1.
Repeat step 1, using the new result: 1 / 2 = 0 and remainder 1. We reached result 0, so we are done.
Step 3: The remainders that we have are 011. We reverse their order and we get the final result: 110
610 = 1102
Try to convert several numbers in the range of 5-30 and then test your result with the tool above.
The source code of the implementation in C of the decimal to binary converter is available in our repository on GitHub.
You can also download the source code of the example implementation from here: dec-to-bin-.zip
We cannot save the result in a natural way, because we don't have a data type for binary values. For that reason we use a character array to keep the ones and zeros.
We start, by allocating the memory for the result. We allocate 65 bytes, because the biggest number that we expect to convert through the long decimal variable is 64 bits. We allocate one additional byte for the null character that will interrupt the string.
Next we check if the memory is allocated correctly and if all is OK we move on.
We want to be smart and put the remainders in reversed order. We do that, so once we are done with the divisions there will be no need to rearrange the result. That's why the next thing we do is to move the pointer to the last character in the allocated memory. This character will be the stop character, so we set it to null.
From here on we have several options. The obvious one is to divide the number until we reach zero. Another option is to use bitwise operations. Let's use the first option, because it is closer to the algorithm that we described above.
We organize the while loop that will repeat the divisions until we reach 0. Now each next division will write the remainder to the left of the previous.
Once the loop completes, we are done and return the result.
Note, that this implementation is for learning purpose. Once you know how to create your own decimal to binary converter you should use the function from the standard library:
See also: How to convert from: