统计一个十六位字中1的个数的汇编小程序
思路:利用逻辑左移指令shl的功能:
如 shl ax, 1 将ax中的最高位放在psw中CF中,然后,将其余的位依次左移一位,最后一位用0填充。
该字为16位,逻辑左移16次,就可以把该字中的所有位都依次放入了CF, 统计这十六次移位中CF位为1的个数,
也就是该字中二进制表示中1的个数, 同时,16次逻辑左移后,该字就被填充为0000h , 可以通过测试其是否为0,作为退出条件。
编码如下:
- ;例 5.2 在addr单元中存放着数y(十六位的字)的地址,试编制一程序把Y中1的的个数存入到单元count中
- data segment
- org 10
- number_y dw 8877h
- addr_y dw ?
- count db ?
- data ends
- code segment
- assume cs:code, ds:data
- start:
- mov ax, data
- mov ds, ax
- mov bx, offset number_y
- mov addr_y, bx
- mov bx, addr_y
- mov ax, word ptr [bx]
- mov cl, 0
- next:
- test ax, 0ffffh
- jz exit
- shl ax,1
- jnc next
- inc cl
- jmp next
- exit:
- mov count, cl
- mov dl,cl
- add dl, 30h
- mov ah,02h
- int 21h
- mov ah, 4ch
- int 21h
- code ends
- end start
- ;例 5.2 在addr单元中存放着数y(十六位的字)的地址,试编制一程序把Y中1的的个数存入到单元count中
- data segment
- org 10
- number_y dw 8877h
- addr_y dw ?
- count db ?
- data ends
- code segment
- assume cs:code, ds:data
- start:
- mov ax, data
- mov ds, ax
- mov bx, offset number_y ; move the relatvie address of number_y to bx
- mov addr_y, bx ; move the address in bx to addr_y memory unit
- mov bx, addr_y ; move the content of addr_y memory unit to bx
- mov ax, word ptr [bx] ; mov the number_y to ax indrectly!
- mov cl, 0 ; init cl 0, for count the 1 in the ax (number_y)
- next:
- test ax, 0ffffh ; test ax is zero?
- jz exit ; if 0 , all bits has been tested, exit it
- shl ax,1 ; logical shift left, the highest bit is putted into CF
- jnc next ; if CF=0, the highest bit is 0 ; continue
- inc cl ; if cf=1, the hightest bit is 1, so increase cl
- jmp next ; contine
- exit:
- mov count, cl ; save the number of 1 in ax to the memory unit count
- ; display the number in the memory unit count , assume its value little to 10
- mov dl,cl
- add dl, 30h
- mov ah,02h
- int 21h
- ; the exit system call
- mov ah, 4ch
- int 21h
- code ends
- end start