Calculate 2's complement of a number in assembly language
A short program to find the binary representation of any signed interger number.
What is two's complement?
Two's complement is an operation that converts a positive binary number to its equivalent negative number. Computers store negative numbers in 2's complement form. To learn more on 2's complement, visit this Wikipedia link.
How to calculate two's complement?
Calculating two's complement is very easy. You can easily follow these steps to get 2's complement of a number.
- Convert the number to its binary form.
- Complement the binary number, or invert each bit of the binary number. The resultant form is also known as 1's complement form.
- Now add
1
to the 1's complement form. The result of this is the 2's complement form.
Let's say, we want to get the binary value -5
. Then, we first convert positive 5
to its binary form. The binary of 5
is 0000 0101
(assuming 8-bit binary).
5 = 0000 0101
1's complement = 1111 1010
Add 1 = + 1
------------------------------
2's complement = 1111 1011
So, the binary representation of -5
is 1111 1011
, or in hexadecimal, it's FB
.
Here's an interesting fact, converting integer 0
to its 2's complement form gives back 0
. So, 0
and -0
have the same value in 2's complement form.
Write the assembly program
Let's write an assembly program to convert this logic into code. For this, we must create a .asm
file and save the number 5
in a register. I'm using emu8086 to write this code.
MOV BL, 5 ; Store 5 in BL register
NOT BL ; Complement the value in BL register
ADD BL, 1 ; Add 1 to the value in BL and store the result in BL register
That's it. Now, we have the result of -5
stored in the BL register. You can output this result or do some more calculation. Here's an output screenshot of my code highlighting the BL register after calculation. It is displaying FB
which is 1111 1011
in binary.
There's also another shorter way of calculating 2's complement using the NEG
operator. The previous code can be written as:
MOV BL, 5
NEG BL
That's it! The NEG
operator will accept a single operand register, calculate 2's compliment of the value, and store the result back in the same register.
You can view the full code in GitHub.
Summary
It is easy to calculate 2's complement in assembly language. We just need to use NOT operation and ADD 1 to get the result.