1

If I were to try to calculate the number of 1's in the dw data, how would I go about that? I want to store the number of 1's in memory sum. I am using EBE to code in 64 bit Assembly Language.

segment .data
       data     dw  1011011011001010b
       sum  dq  0
       size     db  16

segment .text
global main
main:
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
puyopop
  • 27
  • 5
  • 1
    Sufficiently modern CPUs have the `POPCNT` instruction which does exactly this: `popcnt ax, word [data]` will leave 9 in `ax`. – Nate Eldredge Nov 18 '20 at 20:32
  • 1
    For lots of other algorithms, see https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109025#109025 – Nate Eldredge Nov 18 '20 at 20:46

1 Answers1

1

Below is a simple code that counts the 1's in the datum:

  movzx edx, word [data]
  xor   eax, eax           ; RAX=0 CF=0
more:
  adc   eax, 0
  shr   edx, 1
  jnz   more
  adc   eax, 0
  mov   [sum], rax

And this snippet counts the 0's in the value at data. It works by subtracting the number of 1's from the number of available bits in data (stored in size).

  movzx edx, word [data]
  movzx eax, byte [size]
  clc                      ; Keeps first SBB from subtracting (first time only)
more:
  sbb   eax, 0
  shr   edx, 1
  jnz   more
  sbb   eax, 0
  mov   [sum], rax
Sep Roland
  • 33,889
  • 7
  • 43
  • 76