彙編程式:統計一個字的二進位制表示中1的個數
阿新 • • 發佈:2019-02-12
統計一個十六位字中1的個數的彙編小程式
思路:利用邏輯左移指令shl的功能:
如 shl ax, 1 將ax中的最高位放在psw中CF中,然後,將其餘的位依次左移一位,最後一位用0填充。
該字為16位,邏輯左移16次,就可以把該字中的所有位都依次放入了CF, 統計這十六次移位中CF位為1的個數,
也就是該字中二進位制表示中1的個數, 同時,16次邏輯左移後,該字就被填充為0000h , 可以通過測試其是否為0,作為退出條件。
編碼如下:
Code:- ;例 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