用汇编语言编写一个程序,从键盘输入二位十六进制数,统计其对应的二进制中含1的个数,并在下一行以十进制显示出来。
时间: 2023-12-22 21:02:42 浏览: 38
以下是用 x86 汇编语言编写的程序:
```assembly
section .data
msg db 'Enter a 2-digit hex number: '
len_msg equ $-msg
count_msg db 'Number of 1s in binary: '
len_count_msg equ $-count_msg
section .bss
num resb 1
binary resb 8
count resb 1
section .text
global _start
_start:
; print message to prompt user for input
mov eax, 4
mov ebx, 1
mov ecx, msg
mov edx, len_msg
int 0x80
; read input from user
mov eax, 3
mov ebx, 0
mov ecx, num
mov edx, 2
int 0x80
; convert hex input to binary and count number of 1s
mov al, [num]
mov bl, al
shr bl, 4 ; upper nibble
call count_ones
mov byte [count], al
mov bl, al
mov al, [num]
and al, 0x0f ; lower nibble
call count_ones
add byte [count], al
; convert binary count to decimal and print result
mov al, [count]
mov bl, 10
div bl ; divide by 10
add al, '0' ; convert remainder to ASCII
mov byte [binary+7], al
mov al, ah
add al, '0' ; convert quotient to ASCII
mov byte [binary+6], al
mov eax, 4
mov ebx, 1
mov ecx, count_msg
mov edx, len_count_msg
int 0x80
mov eax, 4
mov ebx, 1
mov ecx, binary
mov edx, 8
int 0x80
; exit program
mov eax, 1
xor ebx, ebx
int 0x80
count_ones:
; count number of 1s in binary representation of input
push ebp
mov ebp, esp
mov ecx, 8
mov ebx, 0
count_loop:
shl al, 1 ; shift left
jnc zero_bit
inc bl ; increment count if bit is 1
zero_bit:
loop count_loop
mov eax, ebx
pop ebp
ret
```
上述程序使用系统调用来读取用户输入和输出结果。它将输入的十六进制数转换为二进制,并计算其中包含的 1 的数量,然后将结果以十进制格式打印出来。