Write a program that translates an integer consisting of upto 4 binary
digits into its binary equivalent.
Input:
- xxxx where each x is either a 0 or 1
- there could be 1, 2, 3, or 4 digits
Processing:
- Use remainders to strip off each of the possibly 4 digits
- It really doesn't matter if there are 1, 2, 3, or 4 digits
since the remainder would just be 0
- Using the example of 1010, divide by 1000. The integer result is a 1.
This is your left most digit
- If you take the remainder of 1010 after dividing by 1000, then the answer
is 010 or 10.
- Divide 10 by 100. The integer result is a 0.
This is your second digit
- Take the remainder of 010 after dividing by 100, then the answer
is 10.
- Do you see a pattern evolving?
Output:
- the decimal equivalent of the binary number xxxx
- For example 0011 would result in a 3 being displayed
How to make this work
- The secret is in the division AND being able to change the original number.
- In programming, when you divide an integer by another integer, the decimal
part is truncated.
Consider this code snipet:
int binary_string;
int digit4;
digit4 = binary_string/1000;
Since this is integer division the 010 of 1010
will be truncated and digit4 will
be a one.
- Now, how to extract the remainder after division... We could use
a mathematical formula (originalNumber - digit4*1000), or we could use
C++ builtin operator for modulus(remainder). The % sign is this operator.
binary_string % 1000 will result in 010 the remainder after division.
- We want the new binary_string that we are going to work with to be
changed from 1010 to 010.
binary_string = binary_string % 1000;
Code
Output
- Now repeat for the other digits
Code
Output
Now that the binary number is split apart, how do we change the digits
into the decimal equivalent?
Notice that digit4 is the 8's place holder, digit 3 is the 4's place holder,
digit2 is the 2's place holder and the result in binary_string is the 1's
place holder. So, we could use:
digit4*8 + digit3*4 + digit2*2 + binary_string
Here's the code
Here's the Output
OR
digit4*(2*2*2) + digit3*(2*2) + digit2*(2) + binary_string
Notice that digit4 is multiplied by three 2s, digit3 by two 2s,...
Here's a neater solution
and the output
Notice that the binary string that is printed at the end of the code
is incorrect. We need to print it at the beginning instead.
solution
and output