Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

assembly language rookie

Hello all
I am just getting started in assembly language, and I need a little help with this problem (below). I know how to get the number in the dx reg, but how do you count the binary ones an put them in AL, the text book I have doesnt explane it.
Thanks for your help


Place any binary number is register DX and count the number of binary ones in the number in DX in register AL

Comments

  • anthrax11anthrax11 Member Posts: 511
    shl is an instruction that shifts all bits in a register to the left. The last bit that is shifted out of the register is stored in the carry flag, which you can check with jc/jnc or use adc(add with carry) to increment the counter.

    [code]
    mov dx, n
    xor al, al ; al = 0

    count_loop:
    shl dx, 1 ; shift left by 1 bit
    adc al, 0 ; al = (0 + carry bit)
    or dx, dx ; go back if dx != 0
    jnz count_loop
    [/code]
    There are more ways to do this, but I think this is the easiest. The only problem is that dx is clobbered (becomes 0). If needed, you can store dx in some other register and use that for calculating.
    Here's an older discussion on this subject:
    http://www.programmersheaven.com/mb/x86_asm/369466/369466/counting-number-of-bits-set/
  • TyeboneTyebone Member Posts: 2
    Thanks so much for your help
    Tye
Sign In or Register to comment.