Assembly (x86): Number of '01' repetitions in binary code of HEX number

239 views Asked by At

I'm new to Assembly and I have a task to determine a number of 01 repetitions in a binary code of a 16b hex number. For example:

Number AB34 is: 1010 1011 0011 0100

As 01's are bolded above, they need to be counted and stored in RESULT in the code below. The trick is to only use logical instructions such as AND, NOT, OR, XOR, moving (SHL, SHR), rotating (ROR/RCR, ROL/RCL) and logical comparing.

Here is what I have:

name program

data segment
    BR dw 0AB34H ;
    RESULT db 0
data ends

code segment
    assume CS:code, DS:data
start:
    mov ax, data
    mov ds, ax

    mov ax, BR
    mov cx, 16
    mov bx, 0

lwhile:
    ; something with logical instructions
loop lwhile

    mov RESULT, bl

    mov ah, 4ch
    int 21h
code ends

end start

I'm assuming that inside the loop some work needs to be done, counted through some register like bx and then moved to RESULT.

I'm open to any suggestions, thanks in advance.

1

There are 1 answers

4
lurker On BEST ANSWER

You should making ample use of the and, cmp and shr instructions. Look them up and try them out.

Overall, your code would have a structure like this:

  1. Copy the BR value to a working register (e.g., bx)
  2. Check the lowest two bits for 01 and increment your counter if they are
  3. Shift working register to the right by one bit
  4. Go to 2 [do this 15 times, as there are 16 bits in BR and you're checking pairs of bits]

I'm leaving some details to you. Part of your code inside step 2 might look like this:

    mov  ax, bx        ; Current shifted value of BR
    and  ax, 03h       ; Mask out (zero) all but the lowest two bits
    cmp  ax, 1         ; Check if the lower two bits are 01
    jne  next_bits     ; Jump if nonzero (no, they are not 01)

    ; increment your counter here

next_bits:
    ...

cmp will check if the current pair of bits that have been shifted down to the lower order two bits are 01. To check the next pair of bits, use the shr instruction. Your loop would continue shifting by one bit until you've exhausted all the bits in the working register.