Binary Arithmetic Guide: Learn Binary Math
Introduction:
Welcome back to the second part of the binary tutorial, a tutorial written using plaintext and accessibility in mind. In the first part, I covered how to convert between binary and decimal numbers and vice versa, and provided some code examples to make the computer do the task. If you haven't read that part yet, go here and then come back to this second part.
In this part, I will be covering arithmetic. This is important because not only it will give you an understanding of how exactly computers calculate at the lowest level, but you also need to pay attention to addition and subtraction since those will be important when we reach negative numbers. I have provided the operators in the first part, so I will not repeat them here.
Adding two binary numbers:
If you are someone like me, a person who can't see, then it is likely that you will try to do math mentally. Meaning if someone asks you to add 65 and 54, you will add 60 and 50, which equals 110. Then you will add 5 and 4, which equals 9. Then you put the result together, which equals 119.
Unfortunately, you cannot perform binary arithmetic using mental math tricks. It is limited to only two digits: 0 and 1, and this makes it very difficult to perform any arithmetic operation on two binary strings mentally.
Instead, I suggest you note down the two strings with the operation to be performed on something like Notepad on Windows, and then do it step by step, as I will show you now.
But before I can do that, here are some simple rules:
0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 10 (which means 0, carry 1)
Here's the first example: adding 01 + 01
01 + 01
Start from the rightmost digit, which is 1 for both. 1 + 1 is equal to 10.
Write down 0, and carry the 1.
0 (carry 1)
Now, move on to the digit to the left, which is 0: 0 + 0 = 0.
Then add the carry:
0 + 1 = 1
Put this 1 down with the result: resulting in 10, which is the binary value of 2.
The second example: add 11 + 10
Follow the step of adding the rightmost digits: 1 + 0 is 1, so right down 1, there is nothing to carry here.
Add the next digits to the left (including the carry, if there is any): 1 + 1 = 10
Put the 10 down with the result where there is already a 1: the result is 101, the binary value of 5.
So far, we have seen the binary numbers with equal numbers of digits. One of the two strings is no longer than the other. But what if you have one string that is larger than the other one?
Like in our third example: 100 + 10.
Here, the first string is larger than the second string, having one extra digit.
In this case, you Align the two strings with the rightmost digit, and add a zero to the left of the shorter digit to pad it out. So, the problem becomes like this: 100 + 010.
Now, perform the binary addition as usual:
0 + 0 = 0 (no carry)
Next column:
0 + 1 = 1 (No carry, again)
The final column:
1 + 0 = 1.
So, the final result is 110, which is the value of 6.
That's it. I suggest to get the concept down, you practice with two-digit binary strings, and once you feel good enough about your consistency, move on to the three or more digits.
Subtraction:
Binary subtraction works just like addition, except it uses the concept of borrowing instead of carrying. It shouldn't be a surprise, given subtraction is the inverse of addition.
Example: subtract 01 from 11 (3 and 1)
Subtract from the rightmost column:
1 - 1 = 0
Next column, moving to the left:
1 - 0 = 1
Put it all together:
10 (2)
Another example: subtract 11 from 100 (4 - 3)
Since 100 has three digits and 011 has two, we pad 011 with a leading 0 to match the length:
100
- 011
Step 1: Start from the rightmost column
We need to subtract 0 - 1, but we cannot subtract 1 from 0 directly. This means we need to borrow from a higher place value.
Step 2: Borrowing
The middle column is 0, so we can't borrow from there either. Instead, we borrow from the leftmost 1. This changes the leftmost 1 (which represents 4 in decimal) to 0, the middle 0 becomes 10 (which is 2 in decimal), and since we still need to borrow, the rightmost 0 also turns into 10. Now, the subtraction looks like this:
0 10 10
- 0 1 1
Step 3: Perform Subtraction
The rightmost column is 10 - 1 = 1. The middle column is 1 - 1 = 0. The leftmost column is 0 - 0 = 0. Thus, the final result is:
001
This is 1 in decimal, which is the correct result for 4 - 3.
Multiplication:
Here are the rules of multiplication:
1 * 1 = 1
0 * 0 = 0
1 * 0 = 0
0 * 1 = 0
You will notice that the rules are just as same as the decimal multiplication, the only difference is that we have just two digits in the binary system instead of 10 in the decimal system.
The real challenge comes in when you are shifting and adding, just like in normal multiplication.
Let's look at an example. Multiply 10 (2 in decimal) with 3 (11 in decimal):
Multiply 10 by 1 (since the rightmost digit is 1, the result is just 10).
10 * 1 = 10
Note down the 0, and carry the 1.
Then multiply 10 with 1, since the digit to the left is also 1: 10 * 1 = 10.
Add the carried-over 1, and when you add it together, it becomes 110, the value of 6.
Division:
The binary division follows the same process as a decimal long division but with only 0s and 1s. Instead of checking how many times a number fits, you only check whether the divisor "fits" (1 time) or not (0 times).
In decimal, 10 ÷ 2 = 5, so the result should be 101 in binary.
The binary value of 10 is 1010. First, look at the first 2 digits (10). Since 10 is the same as the divisor, 10 / 10 = 1. So, write 1 in the quotient.
Then, subtract and bring down the next digit. 10 - 10 = 0. Bringing down the next digit makes it 01.
But 01 is smaller, so we write 0 in the quotient.
Bring down the last digit 0, making it 10 again. Divide: 10 / 10 = 1.
Thus, the final result is 101.
If you are blind like me, here's a tip: learn to convert the numbers from binary to decimal, then perform whatever arithmetic is asked of you. Then convert the result to binary again. In the end, nobody cares how you did it. The right answer is the only thing that matters. However, your college professors are unlikely to give you marks for this workaround.
The reason why I suggest this approach is because I myself am used to doing math mentally. True, I take advantage of writing. Whenever I have to do some long multiplication or division, I often note it down on the notepad so I can keep track of values. But in binary, it is going to be very difficult. Given how most of us are not used to working with binary mentally, it is just asking for extra trouble.
Besides, once you note it down, the conversion process back and forth is easier compared to the standard method for us. Still, I suggest you work it out, and see how you like it. You always have this suggestion to fall on should you need it.
Making the computer do it:
What is better than calculating by hand?
Why, make the computer do it of course!
Below are the Python functions for performing all the four arithmetic operations:
def binary_add(bin1: str, bin2: str) -> str:
"""Adds two binary numbers and returns the result as a binary string."""
return bin(int(bin1, 2) + int(bin2, 2))[2:]
def binary_subtract(bin1: str, bin2: str) -> str:
"""Subtracts the second binary number from the first and returns the result as a binary string.
Assumes bin1 is greater than or equal to bin2."""
return bin(int(bin1, 2) - int(bin2, 2))[2:]
def binary_multiply(bin1: str, bin2: str) -> str:
"""Multiplies two binary numbers and returns the result as a binary string."""
return bin(int(bin1, 2) * int(bin2, 2))[2:]
def binary_divide(bin1: str, bin2: str) -> str:
"""Divides the first binary number by the second and returns the quotient as a binary string.
Assumes bin2 is not zero."""
return bin(int(bin1, 2) // int(bin2, 2))[2:]
You will notice that these functions take the approach of converting the binary string into decimal numbers, performing the operation, and then converting it back to the binary string.
The reason for me to take this approach is because I would have to implement the rule of carry forward and borrowing, which would make the code difficult to understand. I am writing these posts for beginners, so I expect that they will be the ones who would be reading it. This approach is a good compromise, because the code is readable, and I am not using any obscure Python method or syntax to accomplish the task.
I've put these functions together, resulting in a binary calculator which you can look at below:
def binary_add(bin1: str, bin2: str) -> str:
"""Adds two binary numbers and returns the result as a binary string."""
return bin(int(bin1, 2) + int(bin2, 2))[2:]
def binary_subtract(bin1: str, bin2: str) -> str:
"""Subtracts the second binary number from the first and returns the result as a binary string.
Assumes bin1 is greater than or equal to bin2."""
return bin(int(bin1, 2) - int(bin2, 2))[2:]
def binary_multiply(bin1: str, bin2: str) -> str:
"""Multiplies two binary numbers and returns the result as a binary string."""
return bin(int(bin1, 2) * int(bin2, 2))[2:]
def binary_divide(bin1: str, bin2: str) -> str:
"""Divides the first binary number by the second and returns the quotient as a binary string.
Assumes bin2 is not zero."""
return bin(int(bin1, 2) // int(bin2, 2))[2:]
choice = int(input("Choose an option to perform a binary operation: 1 for adding, 2 for subtracting, 3 for multiplication, 4 for division:"))
match choice:
case 1:
bin1 = input("Enter the first binary string:")
bin2 = input("Enter the second binary string:")
print("The result is", binary_add(bin1, bin2))
case 2:
bin1 = input("Enter the first binary string:")
bin2 = input("Enter the second binary string:")
print("The result is", binary_subtract(bin1, bin2))
case 3:
bin1 = input("Enter the first binary string:")
bin2 = input("Enter the second binary string:")
print("The result is", binary_multiply(bin1, bin2))
case 4:
bin1 = input("Enter the first binary string:")
bin2 = input("Enter the second binary string:")
print("The result is", binary_divide(bin1, bin2))
case _:
print("Your option is invalid")
I say it is pretty neat. Initially, Python didn't have a switch statement, so if else had to be used. But now, it has a match construct like Rust, which I have used to provide the branches for the choices by the user.
How do you like this part? Share it in the comments. You can read my non-technical blog here, and my web serial novel here. And I will see you in the next part, where we will tackle the negative numbers.