0

i need to find a way to check number of bits that is current on (1) in the ax register. i was thinking to use in shl or shr, but i do not know how exactly i suppose to use them. this is my code so far:

org 100h

mov ax, 0xffffh
;shr ax TO DO

int 16h
ret

i red in some place that the shift right function can move the bits to the right. so i might should use it by try to "push" the 16 bits to the right every time, and then check the LSB 1 or 0 flag? it sound to me as good idea.

Jester
  • 56,577
  • 4
  • 81
  • 125
Mark green
  • 43
  • 9
  • 3
    Yes, that is possible. Also note that `shr` puts the bit shifted out into the carry flag so you can easily count that using `adc`. There are more efficient algorithms of course. – Jester Nov 07 '17 at 15:44

2 Answers2

2

Use the popcnt instruction:

popcnt bx,ax

This sets bx to the number of bits set in ax. You need a somewhat recent CPU for this instruction to be available though.

fuz
  • 88,405
  • 25
  • 200
  • 352
1

The shifted bit goes in the CF(carry flag) so one solution is that everytime after each shift you check that if CF=1 then increment a count variable that will tell the num of ON bits at the end.

Asim
  • 1,430
  • 1
  • 22
  • 43