- Asked 2/19
- 2079 Asoj · 4 marks
Count number of 1s in ROM data
Short answer
Read the byte at ROM 0075H using MOVC. Rotate left through carry eight times, incrementing a counter on each carry = 1. Store the count in RAM 45H. Example: B7H yields 06H.
Write an assembly program for 8051 to count number of 1's in an 8-bit data stored in ROM at 75H and store result in RAM at 45H.
The byte stored in code memory (ROM) at 0075H is read with MOVC. It is rotated through the carry flag eight times, and the counter is incremented each time the carry is 1. The result goes to RAM location 45H.
ORG 0000H
MOV DPTR,#0075H ; DPTR points to the data byte in ROM
CLR A ; offset = 0
MOVC A,@A+DPTR ; A = byte stored at 0075H
MOV R0,#8 ; 8 bits to test
MOV R1,#0 ; R1 = count of 1s
NEXT: RLC A ; move MSB into carry
JNC SKIP ; carry = 0 -> bit was 0
INC R1 ; carry = 1 -> count it
SKIP: DJNZ R0,NEXT ; repeat for all 8 bits
MOV 45H,R1 ; store result in RAM 45H
HERE: SJMP HERE
ORG 0075H
DB 0B7H ; example data 10110111B
END
How it works:
MOVC A,@A+DPTRwith A = 0 reads the ROM byte at DPTR = 0075H.RLC Ashifts the MSB into carry;JNC SKIPskips the increment when the bit is 0.DJNZ R0,NEXTrepeats for 8 bits; R1 holds the count, copied to 45H.
Example: data B7H = 10110111B contains six 1s, so 45H = 06H (checked in a simulator). The data byte is placed in ROM with ORG 0075H / DB; the program itself must be shorter than 75H bytes.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Count number of 0s in ROM data · Embedded System, chapter 9 · asked 2×
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9