8051 Program to Find 2’s complement

In this article two Assembly language programs for 8051 microcontroller are explained to find 2’s complement of an 8 bit Number.

8051 Program to find 2’s complement of an 8 bit Number

To find 2's complement of a number stored in register bank

Problem 1

Write an assembly language program to find 2’s complement of a number stored in Register R0 of Register Bank 0 and store the result in R1 of same bank of for 8051 microcontroller.

Algorithm

Finding 2’s Complement of a Number

  1. Select the register bank using PSW register.
  2. Load the number from Register R0.
  3. Invert all the bits of the number to get the 1’s complement.
  4. Add 1 to the 1’s complement to obtain the 2’s complement.
  5. Store the result in Register R1.
  6. Stop

Program

CLR PSW.4 ; Clear bit 4 of PSW register.

CLR PSW.3 ; Select register bank 0.

MOV A, R0 ; Load the number from R0 to Accumulator A.

CPL A ; Complement all bits to get 1’s complement.

INC A ; Increment the 1’s complement to get 2’s complement.

MOV R1, A ; Store the 2’s complement in R1.

Loop: AJMP Loop ; End of program.

Note:

Apart from using INC A instruction you can use ADD A,#01H instruction, which will increase the contents of accumulator by 1.

Tutorial on 8051 Program to Find 2’s complement

To find 2's complement of a number stored in external memory

Problem 2

Write an assembly language program to find 2’s complement of a number stored in memory location 3000H of external memory of 8051 microcontroller and store the result in 3001H.

Algorithm

Finding 2’s Complement of a Number

  1. Initialize the memory pointer.
  2. Load the number from memory location 3000H.
  3. Invert all the bits of the number to get the 1’s complement.
  4. Add 1 to the 1’s complement to obtain the 2’s complement.
  5. Store the result in memory location 3001H.
  6. End the program.

Program

MOV DPTR, #3000H ; Load address of memory location 3000H to DPTR.

MOVC A, @DPTR ; Move data from memory to Accumulator A.

CPL A ; Complement all bits to get 1’s complement.

INC A ; Increment the 1’s complement to get 2’s complement.

INC DPTR ; Load address of memory location 3001H to DPTR.

MOV @DPTR, A ; Store the 2’s complement in memory location 3001H.

Loop: AJMP Loop ; End of program.

Recent posts

Leave a Comment

Your email address will not be published. Required fields are marked *