YASM is there a way to check for specific numbers in a word?

60 Views Asked by At

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:
1

There are 1 best solutions below

0
Sep Roland On

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